C.W.K.
Stream
Lesson 10 of 12 · published

trap: Cleanup on Exit

~10 min · trap, cleanup, exit

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

The catch-all cleanup

trap 'echo cleaning up; rm -f "$lock"' EXIT

trap CMD SIGNAL... runs CMD when the script receives the named signal. EXIT is the special pseudo-signal that fires regardless of how the script ends — normal exit, error, Ctrl+C, kill. The single most reliable cleanup hook in shell.

Common patterns

tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
# ... use $tmpdir freely; it's auto-cleaned

# Lock file
lock=/tmp/myjob.lock
[[ -e "$lock" ]] && { echo 'already running'; exit 1; }
echo $$ > "$lock"
trap 'rm -f "$lock"' EXIT

Multiple signals

# Same handler for several signals
trap 'cleanup' EXIT INT TERM HUP

# Different handlers
trap 'echo "caught Ctrl+C"' INT
trap 'echo "normal exit"' EXIT

Reset / clear

trap - INT restores the default INT handler (terminate). trap '' INT ignores the signal entirely.

Variables in trap

Quote carefully: trap "rm -f $tmpdir" EXIT expands $tmpdir now, when the trap is set. trap 'rm -f "$tmpdir"' EXIT with single quotes expands later, when the trap fires — usually what you want, especially if the variable might change.

Code

Self-cleaning temp directory·bash
#!/usr/bin/env bash
set -euo pipefail
tmpdir=$(mktemp -d)
trap 'rm -rf "$tmpdir"' EXIT
echo "working in $tmpdir"
cp -r src/ "$tmpdir/"
# whatever you do, the temp dir vanishes when this script ends

External links

Exercise

Write a script that creates mktemp -d, traps EXIT to remove it, then intentionally fails halfway. Confirm the temp dir was cleaned up after the script crashed.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.