Bash 5 reference · Shell Builtins and Syntax

trap (Bash builtin)

Run commands when the script exits or receives a signal; the standard way to clean up temporary files and child processes.

Bash 5

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

trap 'COMMANDS' EXIT | ERR | INT | TERM

Parameters

ParameterDescription
EXIT When the shell exits, for any reason.
ERR When a command fails (with set -e).
INT TERM Signals: Ctrl+C, termination.

Examples

Clean up on exit
bash -c 'tmp=$(mktemp); trap "rm -f $tmp; echo cleaned up" EXIT; echo working; exit 3'; echo "status $?"

Output

working
cleaned up
status 3

Run this on your computer — see “Get Started” for setup.

Report errors
bash -c 'trap "echo failed at line \$LINENO" ERR; set -e; true; false'; echo "status $?"

Output

failed at line 1
status 1

Run this on your computer — see “Get Started” for setup.

Was this page helpful?