I'm writing a shell function that will be called from many different places and I want to ignore all errors occurring inside the function disabling the (possibly enabled) set -e shell option, executing set +e.

The problem is that I don't know if that option was set or not, so I don't know if it's really needed to disable it, and more important, if I need to set it again at the end.

So, how do I know if it is set or not? Is there any way to ignore errors of all commands inside a shell function ignoring the -e shell option if is set?


Look at the value of $-, if it contains an 'e', then the '-e' option is set. This variable contains a list of all set options. This is described in the bash man page.

  • 5
    You can check with something like [[ $- =~ e ]]. – Ansgar Wiechers Sep 10 '12 at 14:28
  • @AnsgarWiechers your way of checking is way better than mine echo $- | grep -q "e" :) – Trevor Boyd Smith Jul 8 '16 at 16:17
  • [[ $- == *e* ]] – Steffen Heil Jun 6 '20 at 12:04

I like both answers. Ansgar's suggestion works well with bash, Trevor's is good if grep is in the PATH. If you want to be independent of shell (bash/sh) and PATH you could use

[ "${-#*e}" != "$-" ]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.