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.

LinuxtrapbashshellcliHigh risk
Add trap 'rm -rf "$TMPDIR"' EXIT INT TERM near the top of your script so temp files are removed no matter how the script ends.

01Command

Command
$ trap 'rm -rf "$TMPDIR"; echo cleaned' EXIT INT TERM

02What 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

RiskHigh risk
!Warning: Never write trap 'rm -rf $TMPDIR' with unquoted variables and no guard — if TMPDIR ends up empty the handler becomes rm -rf / ; always quote and check for emptiness inside the action.

04Undo

✓No undo needed — this command does not change persistent state.

05Sources

  • signal(7) — Linux manual page
    man7.org · community · 2026-09-17
    Evidence: Reference for SIGINT/SIGTERM semantics, the signals scripts most commonly need to trap for cleanup.
  • bash(1) — Linux manual page
    Arch Linux · community · 2026-09-17
    Evidence: 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