6

I use set -e in scripts quite often, but sometimes, it's ok for a script to fail in some of it's commands.
I tried checking if set -e was ON, but couldn't find a way to do it - there's no option (that I know of) in set that will provide the current value.
Also tried this: set | grep errexit (errexit is the option name for -e) and set | grep "-e", no luck there.
I would like to check if the errexit option is set, so I could temporarily disable it in some of my library functions that I built over time (using set +e and re-applying set -e if needed). Something like:

if [ errexit is set ]; then
   ERR_EXIT=1
   set +e
fi
...
run some code that may fail
...
if [ "${ERR_EXIT}" = 1 ]; then
    set -e
fi
  • This doesn't strictly answer your question, but remember you can always do things like `cmd || true` to stop the script from exiting if `cmd` fails, or even better: you can make `cmd` the subject of an `if` statement that deals with its failure. – Izaak van Dongen Oct 20 '20 at 08:09
  • 1
    Thanks @IzaakvanDongen ,I know that, it doesn’t help when the main script uses ‘-e‘ and some library function I wrote years ago explicitly checks ‘$?‘ – Moshe Gottlieb Oct 20 '20 at 08:15
  • 1
    Also: https://superuser.com/questions/997755/is-it-possible-to-check-whether-e-is-set-within-a-bash-script/997776, https://superuser.com/questions/1034770/how-to-check-shell-options, – muru Oct 20 '20 at 10:33
  • Thanks @muru ! Already using glenn-jackman 's answer, but user1686 and the answers you pointed out are also correct. – Moshe Gottlieb Oct 20 '20 at 10:36

2 Answers2

8

You check if the $- variable contains e

if [[ $- == *e* ]]

See Special-Parameters in the manual.


For POSIX shells, case is the builtin tool for pattern matching

case $- in
*e*) doSomething ;;
esac
glenn jackman
  • 25,463
  • 6
  • 46
  • 69
  • 1
    You might want to read http://mywiki.wooledge.org/BashFAQ/105 for some interesting discussion about the use of `set -e` – glenn jackman Oct 19 '20 at 16:40
3

Within bash (but not basic sh), you can use shopt -o -p errexit. Its output can be stored and later eval'd to restore the initial value. (It will also return 0 if the option is set, 1 otherwise.)

errexit will also not trigger in several cases even if enabled, such as if the failing command was used together with || – for example this_can_fail || true will let you ignore just that command.

It will also not trigger if the command was part of an if condition, e.g. if ! this_can_fail; then echo "Warning: it failed"; fi.

u1686_grawity
  • 426,297
  • 64
  • 894
  • 966