Is it possible to check whether -e is set within a bash script?
Solution 1:
You have the flags currently set in the variable $-
, so you can preserve this
at the start of function and restore it after.
save=$-
...
if [[ $save =~ e ]]
then set -e
else set +e
fi
Solution 2:
You can read the flag value thru the variable SHELLOPTS:
> set +e
> echo $SHELLOPTS
braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor
> set -e
> echo $SHELLOPTS
braceexpand:emacs:errexit:hashall:histexpand:history:interactive-comments:monitor
You see that, after setting set -e
, the value errexit
in $SHELLOPTS
appears. You can check it from there.
However, you can get around this (if you wish!) by remembering the following point: according to the Manual:
-e:
..... This option applies to the shell environment and each subshell environment separately.
Thus, if you execute your function in a subshell, like
zz="$(myfunction)"
you do not have to worry whether the errexit
variable is set or not in calling environment, and you may set it as you like.
Solution 3:
Another way would be to use the shopt
builtin (with the -o
flag, to access the right set of options, from set -o
; and the -q
flag, to just quietly provide the setting via the exit code from shopt
). So, something like this:
# save the previous "set -e" setting
shopt -oq errexit && set_e_used=$? || set_e_used=$?
set +e
...your code here...
# restore the previous "set -e" setting
if [[ $set_e_used -eq 0 ]]; then
set -e
else
set +e
fi