M BUZZ CRAZE NEWS
// general

In a bash script, how do I check if "-e" is set? [duplicate]

By Jessica Wood

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
4

2 Answers

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

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.