🎓 A1Learner
🔍
0 of 45 lessons completed

Bash Trap on Error

An ERR trap is a handler that runs when a command fails. It reports the failure at once, but it does not by itself fix or undo the failure.

A failing command triggers the trap

The false command fails, so the trap prints its line. Without set -e, the script then keeps running to the next line.

trap 'echo "error caught"' ERR
false
echo "still running"

A failure tested by if does not trigger the trap

The failing command sits inside an if test, so the trap stays silent. The else branch handles the failure instead.

trap 'echo "error caught"' ERR
if false; then
  echo "then branch"
else
  echo "handled by if"
fi
echo "done"

With set -e, the trap runs and then the script exits

The trap prints its line when the command fails. Because set -e is active, the script exits at once and the last line never prints.

set -e
trap 'echo "error caught"' ERR
false
echo "never printed"

Example

trap 'echo "failed: $BASH_COMMAND" >> errors.txt' ERR
echo "good step done"
cat missing.txt 2>/dev/null
echo "recovered"
cat errors.txt

Key points

  • Trigger: an ERR trap runs when a simple command returns a non-zero status.
  • Continue by default: without set -e, the script keeps running after the trap.
  • Condition exception: a failure inside an if or while test does not trigger the trap.
  • Set -e interplay: with set -e, the trap runs first, then the script exits.
  • Errtrace: set -E so an ERR trap also reaches functions and subshells.
  • Honest limit: an ERR trap reports a failure, but it cannot undo damage the failure already did.

In this example, the ERR trap writes the failing command to an error log when a step fails. The missing-file error itself is silenced, so only the trap record appears in the log. The script then recovers, and the final line shows the logged failing command.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A script has no set -e and its ERR trap prints a warning. What happens after a command fails?