errexit and its exceptions
set -e (errexit) can terminate a noninteractive shell after an unhandled failed command. It is not a general exception mechanism. Bash suppresses this behavior in conditions of if/while/until, nonfinal commands of AND/OR lists, nonfinal pipeline components (subject to the pipeline status), and negated pipelines. If a function is called in a context where errexit is ignored, its body is also affected. In ordinary non-POSIX Bash, command substitutions normally clear errexit; shopt -s inherit_errexit changes that inheritance, and POSIX mode enables it. A surrounding tested context can still suppress the effect. Use separate Bash processes in experiments so the lesson itself survives a child failure. Explicitly guard operations that must succeed. A tested function can explicitly return a failure with step || return "$?", even when errexit is suppressed. Test the function both directly and inside a conditional.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
An unhandled failure
bash -c 'set -e; printf "before\n"; false; printf "after\n"'printf 'child=%s\n' "$?" Expected stdout:
beforechild=1The child exits before after. The outer demonstration shell continues.
A tested function
bash -c 'set -ework() { false; printf "continued\n"; }if work; then printf "reported success\n"; fi'printf 'child=%s\n' "$?" Expected stdout:
continuedreported successchild=0The if test suppresses errexit in the function; the final printf makes work succeed.
Command substitution inheritance
bash -c 'set -e; shopt -u inherit_errexit; v=$(false; printf ok); printf "%s\n" "$v"'printf 'default=%s\n' "$?"bash -c 'set -e; shopt -s inherit_errexit; v=$(false; printf ok); printf "%s\n" "$v"'printf 'inherited=%s\n' "$?" Expected stdout:
okdefault=0inherited=1In the second child the substitution exits on false and the assignment fails.
Common mistakes
Never promise that set -euo pipefail catches all failures. Calling a function in if or || can change how its body responds to failure. Do not rely on a successful final printf to prove prior operations succeeded.
Practice
Compare an unguarded child shell failure with a function called inside if. Rewrite the function to return explicitly on its first failed prerequisite.
Next: nounset and optional parameters