trap ERR for Custom Error Handling
In this page:
A Basic ERR Trap
trap handler ERR registers code that runs automatically whenever a command in the script fails, in the same situations where set -e would normally stop it.
Example: A Basic ERR Trap
#!/bin/bash
(
trap 'echo "an error was trapped"' ERR
set -e
false
echo "unreached"
) || echo "subshell exited after the ERR trap ran"
Login to try C/C++/Java/PHP code in the editor
Reporting the Failing Line Number
Inside an ERR trap, $LINENO reflects the line number where the failure occurred, which makes error messages far more useful for pinpointing the actual bug.
Example: Reporting the Failing Line Number
#!/bin/bash
(
trap 'echo "error occurred near line $LINENO"' ERR
set -e
true
false
) || echo "handled"
Login to try C/C++/Java/PHP code in the editor
Making ERR Traps Work Inside Functions
By default, an ERR trap does not propagate into functions or command substitutions. set -o errtrace (equivalently set -E) extends the trap so it fires no matter where the failure happens.
Example: Making ERR Traps Work Inside Functions
#!/bin/bash
(
set -E -e
trap 'echo "caught failure inside a function"' ERR
fail_inside() {
false
}
fail_inside
echo "unreached"
) || echo "subshell stopped after the function's failure was trapped"
Login to try C/C++/Java/PHP code in the editor
- Assuming
trap ERRfires for commands exempted fromset -etoo (like anifcondition); it shares the same exemptions. - Forgetting
trap ERRonly fires reliably whenset -esemantics are in effect for that command; behavior can otherwise be inconsistent across contexts like functions unlessset -E(errtrace) is also used. - Writing an ERR handler that itself might fail, causing confusing recursive or missed error handling.
trap handler ERRrunshandlerwhenever a command fails, in the same contexts whereset -ewould trigger.set -o errtrace(set -E) makes the ERR trap also fire inside functions and subshells, not just top-level commands.- An ERR trap is commonly used to log diagnostic information (like the failing line number via
$LINENO) before the script exits. - Combining
trap ERRwith an EXIT trap lets you separate error-specific logging from general cleanup that should always run.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first:
- Exit Codes and Checking $? Correctly
- set -e and set -u
- Error Handling
- set -e (Exit on Error) and Its Gotchas
- Logging
- set -u (Undefined Variables) and set -x (Trace Mode)
- Script Arguments with getopts
- trap ERR for Custom Error Handling
- Debug Mode (set -x)
- Writing a Custom Error/die Function
- Portability
- Validating Script Input and Arguments