ERR traps and inheritance
An ERR trap runs on certain failed commands or compound results, even without errexit. It is subject to analogous tested-context exceptions: a failure used by if, a nonfinal AND/OR command, a nonfinal pipeline component, or negation is not an automatic ERR event. set -E (errtrace) makes the ERR trap inherited by functions, subshell environments and command substitutions. An ERR trap may run at more than one level when a failure propagates. It does not catch every expansion or syntax error. Capture $? at the beginning of the handler; keep diagnostics on stderr and avoid printing commands that may contain secrets. A handler that logs does not by itself terminate the script. When pipefail is active, a failing aggregate pipeline can trigger ERR even if its last component succeeds. Without errtrace, a failing function can still trigger ERR for the function call itself.
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.
Log without exiting
trap 'rc=$?; printf "ERR=%s\n" "$rc" >&2' ERRfalseprintf 'still running\n' Expected stdout:
still runningExpected stderr:
ERR=1ERR logging works without -e; the next command still runs.
Tested failure is not an ERR event
trap 'printf "unexpected ERR\n" >&2' ERRif false; then :; else printf 'handled\n'; fifalse || printf 'fallback\n'! trueprintf 'done\n' Expected stdout:
handledfallbackdoneThese failures are in exception contexts; stderr remains empty.
Function inheritance
trap 'printf "ERR=%s\n" "$?" >&2' ERRwork() { false; printf 'work continued\n'; }set +Eworkset -EworkExpected stdout:
work continuedwork continuedExpected stderr:
ERR=1Only the second invocation inherits ERR inside the function. Its last command succeeds, so no additional function-level failure occurs.
Common mistakes
Do not expect ERR to run for every failure or to replace cleanup. Use single quotes around a fixed trap action so $? is evaluated at event time, not registration time.
Practice
Install an ERR handler that prints only the status. Compare false, false in an if condition, and false inside a function with errtrace enabled and disabled.
Next: EXIT, INT and TERM cleanup