13

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?

1

3 Answers 3

20

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.

3
  • 6
    You can check with something like [[ $- =~ e ]]. Sep 10, 2012 at 14:28
  • @AnsgarWiechers your way of checking is way better than mine echo $- | grep -q "e" :) Jul 8, 2016 at 16:17
  • 1
    [[ $- == *e* ]] Jun 6, 2020 at 12:04
2

From man bash:

CONDITIONAL EXPRESSIONS
...
   -o optname
      True if the shell option optname is enabled. 
...

Which means, that this will do it:

if [ -o errexit ]
then
   ....
fi

and is much more clear than the rest of the alternatives.

PS: for optnames, look in man bash for option-name:

-o option-name
...
   errexit Same as -e.
1

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}" != "$-" ]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .