trap EXIT
BashINFOCommonScriptingHIGH confidence

EXIT trap — cleanup on script exit

Production Risk

Best practice for any script that creates temporary resources; prevents resource leaks on failure.

What this means

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.

Why it happens
  1. 1Script exits normally with any exit code
  2. 2set -e causes an early exit
  3. 3A signal terminates the script
How to reproduce

EXIT trap used for temporary file cleanup.

trigger — this will error
trigger — this will error
#!/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 exit

expected 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

Always use EXIT trap for temporary resource cleanup
#!/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.

What not to do

✕ 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.

Sources
Official documentation ↗

GNU Bash Manual — trap

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Bash errors