How to trap signals in Bash
Use Bash trap to catch signals like SIGINT/SIGTERM, run cleanup on EXIT, and handle errors with trap ERR. Copy-paste examples for reliable scripts.
Tldr
Use `trap 'command' SIGNAL` to run code when a script receives a signal. `trap cleanup EXIT` is the standard pattern for guaranteed cleanup (temp files, locks) regardless of how the script exits — normal completion, error, or Ctrl-C. Use `trap '...' ERR` combined with `set -e` to react to any failing command.
Intro
trap lets a Bash script intercept signals (like SIGINT from Ctrl-C) and pseudo-signals (like EXIT and ERR) to run cleanup code reliably instead of leaving temp files, locks, or background jobs behind.
Steps
Name
Trap Ctrl-C (SIGINT) to handle interruption gracefully
Text
Without a trap, Ctrl-C kills the script immediately. Trapping SIGINT lets you print a message or clean up before exiting.
Name
Use trap EXIT for guaranteed cleanup
Text
The EXIT pseudo-signal fires whenever the script ends for any reason — normal exit, an explicit exit call, or an uncaught error under set -e. This is the standard way to remove temp files reliably.
Name
React to any failing command with trap ERR
Text
Combined with set -e, an ERR trap fires on any command that fails, letting you log context before the script exits.
Name
Trap multiple signals with one handler
Text
List several signal names after the command to run the same handler for all of them, useful for treating SIGINT and SIGTERM the same way.
Name
Reset or ignore a trap
Text
trap - SIGNAL restores default behavior; trap '' SIGNAL ignores the signal entirely. Useful when a cleanup section should not itself be interrupted.
Faq
Q
What is the difference between EXIT and ERR traps?
A
EXIT fires whenever the script terminates for any reason (success, error, or explicit exit), making it ideal for cleanup that must always run. ERR fires only when a command fails (with set -e semantics), making it suited for error logging rather than unconditional cleanup.
Q
Does trap EXIT run if the script is killed with SIGKILL?
A
No — SIGKILL (kill -9) cannot be caught, trapped, or ignored by any process, so cleanup code in an EXIT trap will not run if the script is killed that way. Use SIGTERM for a killable-but-catchable shutdown signal instead.
Q
Can I trap a signal only for part of the script?
A
Yes — set the trap before the sensitive section and reset it afterward with `trap - SIGNAL` (restore default) once that section completes, as shown in the ignore/restore pattern above.