jobs

trap

Registers a command to run when the shell receives a signal or special event (EXIT, ERR, DEBUG, RETURN). The workhorse for cleanup handlers, temp-file removal, and error diagnostics in scripts.

trap [ACTION] SIGNAL ...

Common flags / operators

Flag / Operator Purpose
EXIT Run ACTION when the shell/script exits (any reason)
ERR Run when a command returns non-zero (pairs with set -e)
INT / TERM Ctrl-C interrupt / termination signal
-l List signal names and numbers
-p Print current traps in reusable form
trap - SIG Reset SIG to default handling

Examples

trap 'rm -f "$tmp"' EXIT

Guarantee tempfile cleanup regardless of exit path.

trap 'echo failed on line $LINENO' ERR

Diagnostic line-number reporting; pair with set -eE.

trap '' INT

Ignore Ctrl-C for the rest of the script.

trap - INT

Restore default Ctrl-C behavior.

Gotcha

Traps do NOT inherit into functions or subshells by default — use 'set -E' so ERR traps inherit. Single-quote the ACTION so variables like $LINENO expand at trap-time, not registration-time.

Related

← All Bash builtins · Linux commands