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
Syntax
trap 'COMMANDS' EXIT | ERR | INT | TERM
Parameters
| Parameter | Description |
|---|---|
EXIT |
When the shell exits, for any reason. |
ERR |
When a command fails (with set -e). |
INT TERM |
Signals: Ctrl+C, termination. |
Examples
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.
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.
Related
set -euo pipefail· Turn on strict mode: exit on errors (-e), fail on unset variables (-u), and fail pipelines when any part fails.- Bash Error Handling: set -euo pipefail and trap · tutorial