EXIT trap — cleanup on script exit
Production Risk
Best practice for any script that creates temporary resources; prevents resource leaks on failure.
The EXIT trap fires whenever the script exits, regardless of the exit code or reason — including signals, set -e failures, and normal completion. It is the standard pattern for guaranteed cleanup in bash scripts.
- 1Script exits normally with any exit code
- 2set -e causes an early exit
- 3A signal terminates the script
EXIT trap used for temporary file cleanup.
#!/bin/bash
TMPFILE=$(mktemp)
cleanup() {
rm -f "$TMPFILE"
echo "Cleaned up $TMPFILE"
}
trap cleanup EXIT
echo "Working with $TMPFILE"
# Even if the script fails, cleanup runs
false # force non-zero exitexpected output
Working with /tmp/tmp.XXXXXX Cleaned up /tmp/tmp.XXXXXX
Fix
Always use EXIT trap for temporary resource cleanup
WHEN A script creates temporary files, directories, or locks
#!/bin/bash
TMPDIR=$(mktemp -d)
LOCKFILE=/var/run/myapp.lock
cleanup() {
rm -rf "$TMPDIR"
rm -f "$LOCKFILE"
}
trap cleanup EXIT
# Now cleanup is guaranteed regardless of how the script exits
touch "$LOCKFILE"
process_data "$TMPDIR"Why this works
The EXIT trap runs even on unexpected exits, ensuring resources are always cleaned up.
✕ Rely on cleanup code at the end of the script
If the script exits early (via set -e, signal, or explicit exit), code at the end of the script will not run; the EXIT trap always does.
GNU Bash Manual — trap
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev