ERR trap — command failed
Production Risk
Best practice for production scripts; pair with set -o pipefail for comprehensive error capture.
The ERR trap fires whenever a command exits with a non-zero status (similar to set -e, but without killing the script). It is commonly used to log errors, clean up, or send alerts when commands fail.
- 1Any command returns non-zero when an ERR trap is set
- 2Used intentionally by scripts to catch and report all failures
ERR trap fires when a command fails.
#!/bin/bash
on_error() {
echo "Error on line $1: exit code $2" >&2
}
trap 'on_error $LINENO $?' ERR
ls /nonexistent # triggers ERR trap
echo "Script continues"expected output
ls: cannot access '/nonexistent': No such file or directory Error on line 6: exit code 2 Script continues
Fix
Use ERR trap for centralized error handling
WHEN Writing production scripts that need error reporting
#!/bin/bash
set -o pipefail
on_error() {
local exit_code=$1
local line_no=$2
echo "[ERROR] Line $line_no failed with exit $exit_code" >&2
# Optional: send alert, cleanup, etc.
}
trap 'on_error $? $LINENO' ERR
# All commands now have automatic error logging
rsync -av /src/ /dst/
process_resultsWhy this works
The ERR trap receives $? (exit code) at the time of the failure. Combined with $LINENO, it provides useful error context.
✕ Mix trap ERR with set -e without understanding interactions
set -e exits before the ERR trap can run in some cases; test the combination carefully.
GNU Bash Manual — trap
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev