Clean Up Temp Files with bash trap on Exit
Register a cleanup handler that runs when your script exits normally, is interrupted with Ctrl-C, or is killed with SIGTERM.
01Command
$ trap 'rm -rf "$TMPDIR"; echo cleaned' EXIT INT TERM02What it does
trap tells bash to run a command when specific events occur: EXIT fires on any script termination (success, error, or signal), while INT and TERM catch Ctrl-C and kill so the same cleanup runs before the process dies. This single line replaces fragile cleanup code scattered at every exit point of a script. Put the trap right after creating the temp directory, quote the action in single quotes so variables expand at trap-run time, and remember the handler can also send notifications or restore modified files, not just delete things.
03Risk
04Undo
✓No undo needed — this command does not change persistent state.
05Sources
- signal(7) — Linux manual pageEvidence: Reference for SIGINT/SIGTERM semantics, the signals scripts most commonly need to trap for cleanup.
- bash(1) — Linux manual pageEvidence: Documents trap: EXIT runs its action on shell exit, INT/TERM on the corresponding signals; a trap set without arguments resets it.
Last verified: 2026-09-18 · Category: Developer