7

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
6
  • 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. Oct 20, 2020 at 8: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 ‘$?‘ Oct 20, 2020 at 8:15
  • 1
  • Thanks @muru ! Already using glenn-jackman 's answer, but user1686 and the answers you pointed out are also correct. Oct 20, 2020 at 10:36
  • For your particular case, you can do local restore_errexit="$(shopt -po errexit)". The command outputs the code needed to set it back to what it is now. To restore, all you have to do is just run ${restore_errexit}. To just save and restore, it's the most simple way. Jan 17 at 16:42

2 Answers 2

9

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
1
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.

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