trap ERR
BashERRORNotableScriptingHIGH confidence

ERR trap — command failed

Production Risk

Best practice for production scripts; pair with set -o pipefail for comprehensive error capture.

What this means

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.

Why it happens
  1. 1Any command returns non-zero when an ERR trap is set
  2. 2Used intentionally by scripts to catch and report all failures
How to reproduce

ERR trap fires when a command fails.

trigger — this will error
trigger — this will error
#!/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

Use ERR trap for centralized error handling
#!/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_results

Why this works

The ERR trap receives $? (exit code) at the time of the failure. Combined with $LINENO, it provides useful error context.

What not to do

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.

Sources
Official documentation ↗

GNU Bash Manual — trap

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Bash errors