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

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

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.

Tags:

Bash

Exit Code