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.
More on Functions, exit codes, strict mode and traps
How do you define a function, pass arguments and return a value?BeginnerWhat does `local` do, and what is dynamic scoping?AdvancedWhy is `local out=$(cmd)` a problem under `set -e`?AdvancedWhat are the conventional exit codes, and what do 126, 127, 130, 137 and 143 mean?BeginnerExplain `set -euo pipefail` line by line, and add the `-E` flag.BeginnerWhy can `((count++))` kill a script under `set -e`?Intermediate