Interview Prep/Shell Scripting/Functions, exit codes, strict mode and traps

What does `set -e` do, and where does it NOT cause an exit?

AdvancedConceptFunctions, exit codes, strict mode and traps
Answer

set -e (errexit) exits the shell when a command returns non-zero, unless the failure is "checked":

  • in the condition of if, elif, while, until
  • on the left of && or || (only the last command in the list counts)
  • after !
  • in any command of a pipeline except the last (without pipefail)
  • inside a function called from any of the above contexts, even deep inside it
  • in command substitution in older Bash, unless shopt -s inherit_errexit (4.4+)
set -e
check() { false; echo "still running"; }
if check; then echo ok; fi    # prints "still running" and "ok"

So set -e is a safety net, not error handling. Check critical commands explicitly.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Functions, exit codes, strict mode and traps