Trap Handlers for Cleanup and Signals
Register EXIT, ERR, and INT traps to remove temp files and roll back partial work reliably.
Why Trap Handlers Matter
When a Bash script exits — whether normally, due to an error, or because the user pressed Ctrl+C — it can leave behind temporary files, half-written data, or broken state. Without cleanup, these artifacts accumulate and cause hard-to-debug problems.
Trap handlers solve this by registering a function or command that Bash executes automatically when a specific signal or pseudo-signal is received.
- EXIT — fires whenever the script exits, for any reason
- ERR — fires after any command returns a non-zero exit status
- INT — fires when the user sends SIGINT (Ctrl+C)
- TERM — fires on SIGTERM (e.g. from
kill)
A well-written script registers these traps at the very top, before any risky work begins.
The trap Builtin Syntax
The trap builtin registers a handler for one or more signals or pseudo-signals. The general syntax is:
trap 'command_or_function' SIGNAL [SIGNAL...]
Key rules:
- The first argument is a quoted string of shell code (or a function name) to execute when the signal fires.
- You can list multiple signals after the handler.
trap '' SIGNALignores that signal (empty handler).trap - SIGNALresets the signal to its default behavior.
Traps are inherited by functions called in the same shell, but not by subshells spawned with ( ) or &.
#!/usr/bin/env bash
# Syntax examples — not a full script
# Register a cleanup function on EXIT
trap cleanup EXIT
# Inline handler for INT and TERM
trap 'echo "Interrupted!"; exit 1' INT TERM
# Ignore SIGHUP
trap '' HUP
# Reset SIGPIPE to default
trap - PIPEAll lessons in this course
- Strict Mode with set -euo pipefail
- Trap Handlers for Cleanup and Signals
- Safe Temporary Files and Lock Directories
- Idempotent Scripts and Retry-with-Backoff Logic