December 5, 2026

Bash trap EXIT: Cleanup That Runs on Every Way Out, Tested on Six of Them

A steel exit door at the end of a corridor with a mop and bucket beside it

A script that creates a temporary file, a lock or a background process has to remove it again, and the script can end in more ways than its author usually plans for: a normal finish, an explicit exit, a failed command under set -e, Ctrl+C, a kill from somewhere else. One trap line covers nearly all of them. The tests below ran on Bash 5.2.21 and show exactly which exits it catches, which one it cannot, and where the same script behaves differently under sh.

Video: theurbanpenguin on YouTube

The pattern

#!/bin/bash
tmp=$(mktemp)
cleanup() { rm -f "$tmp"; }
trap cleanup EXIT

# ... the real work ...

trap registers a command to run when the shell receives a signal. The Bash manual gives the form as trap [-lpP] [action] [sigspec ...], where the action is read and executed when the shell receives any of the signals listed. EXIT is not a real signal. It is a pseudo-signal the shell provides: if a sigspec is 0 or EXIT, the manual says, the action is executed when the shell exits.

The trap is set right after the resource is created, before anything can go wrong.

Assorted hand tools in a tool rack

Six ways out

The test

A script with that pattern was ended six different ways. After each run a check looked for the temporary file.

How the script ended Exit status Temp file
Ran to the end 0 Removed
exit 3 3 Removed
Command failed under set -e 2 Removed
SIGINT (Ctrl+C) 130 Removed
SIGTERM (plain kill) 143 Removed
SIGKILL (kill -9) 137 Left behind

Five of six. In Bash, an EXIT trap runs when the script is ended by an interrupt or a terminate signal as well as on ordinary exits, so a single line handles all the common cases.

The one that cannot be caught

SIGKILL cannot be trapped by any process. The kernel removes the process without giving it a chance to run anything. No shell technique fixes that, which is one reason to send a plain kill first and reach for kill -9 only when it is ignored. A script that must survive this case needs a check at startup for leftovers from a previous run.

The statuses 130, 143 and 137 follow the shell convention of 128 plus the signal number: 2 for INT, 15 for TERM, 9 for KILL.

dash does not run EXIT on a signal

On Debian and Ubuntu, /bin/sh is dash, not Bash. The identical three-line script, run both ways:

trap 'echo "EXIT trap ran"' EXIT
kill -TERM $$
sleep 1
Shell Output Exit status
bash EXIT trap ran 143
dash (nothing) 143

Under dash the script died on the signal and the cleanup never ran. A script with a #!/bin/sh first line, or one started by a tool that calls sh, gets the dash behaviour.

The portable form

Trapping the signals explicitly and turning them into an ordinary exit makes both shells behave the same:

trap 'echo "EXIT trap ran"' EXIT
trap 'exit 1' INT TERM HUP

With the second line added, both bash and dash printed EXIT trap ran. The signal handler calls exit, and exiting is what fires the EXIT trap. In Bash the order is visible when each handler prints something:

INT trap
EXIT trap

The signal trap ran first, then the exit trap, and the script ended with the status the signal handler chose.

Keeping the exit status honest

The handler can see it

Inside an EXIT trap, $? still holds the status the script was about to exit with, as long as it is read before any other command runs:

cleanup() { local rc=$?; echo "exit status seen by trap: $rc"; }
trap cleanup EXIT
exit 7
exit status seen by trap: 7

The script’s final status was 7 as well. Running cleanup commands in the handler does not change what the caller sees. That makes it possible to clean up differently on failure, for example keeping a log file when rc is non-zero.

The handler can also destroy it

trap 'echo cleaning; exit 0' EXIT
exit 7

That script reported an exit status of 0. An exit inside the EXIT trap replaces the original status, and a script that failed now looks to cron, to CI or to a calling script like one that succeeded. The fix is to leave exit out of the handler, or to capture the status first and end with exit "$rc".

Keys

Quoting decides when variables are read

Double quotes: now. Single quotes: later.

f=one
trap "echo double: $f" EXIT
f=two
double: one

With double quotes the shell expanded $f on the line where the trap was set, and the trap stored the text echo double: one. The later assignment had no effect.

f=one
trap 'echo single: $f' EXIT
f=two
single: two

Single quotes store the text unexpanded, and the variable is read when the trap fires. For cleanup that is almost always what is wanted, since the name of the temporary file or the PID of a background job is often not known until later. Calling a function, as in the pattern at the top, avoids the question.

One trap per signal

The second replaces the first

trap 'echo first' EXIT
trap 'echo second' EXIT
trap -p EXIT
trap -- 'echo second' EXIT
second

Setting a trap on a signal that already has one overwrites it. There is no stacking. In a long script, or one that sources a library with its own trap, an earlier cleanup can vanish without a trace. trap -p prints the current traps in a form that can be reused as shell input, which is how to check. The usual defence is a single cleanup function that every part of the script adds to.

Ignoring and resetting

Two special actions exist. An empty string makes the shell ignore the signal, and a lone dash puts back the original behaviour:

trap '' INT       # Ctrl+C now does nothing
trap - INT        # Ctrl+C works again

In the test, a SIGINT sent after the first line was ignored and the script carried on. One sent after the second line killed it. The manual adds a detail about the ignore form: the signal is ignored by the shell and by the commands it invokes, so child processes inherit it.

A handler that does not call exit behaves differently from both. The script runs the handler and then continues from where it was:

trap 'echo "caught INT"' INT
kill -INT $$
echo "still running after INT"

Both lines printed. A handler written only to log a message turns Ctrl+C into a no-op for the user.

Subshells start clean

trap 'echo "EXIT trap in $BASHPID (main is $$)"' EXIT
( echo "in subshell"; exit 0 )
echo "back in main"
in subshell
back in main
EXIT trap in N (main is N)

The trap fired once, in the main shell, and the two process numbers it printed were the same. The subshell in parentheses exited without running it. The manual states the rule: trapped signals that are not being ignored are reset to their original values in a subshell when one is created.

This is usually the helpful behaviour, since a subshell exiting should not delete the parent’s temporary files. It does mean a subshell that creates its own resources needs its own trap.

Mechanical parts

The ERR trap

Reporting what failed

ERR is another pseudo-signal. Its action runs whenever a command returns a non-zero status, and two built-in variables make it a cheap error reporter:

trap 'echo "ERR at line $LINENO: $BASH_COMMAND (status $?)"' ERR
true
false
ls /nonexistent 2>/dev/null
if false; then :; fi
false || echo "handled"
echo end
ERR at line 3: false (status 1)
ERR at line 4: ls /nonexistent 2> /dev/null (status 2)
handled
end

What it skips

Two failing commands were reported and two were not. The false inside the if test and the false on the left of || passed without a message. The manual lists the exemptions: a command in the test after if, elif, while or until, a command in an && or || list other than the last one, any command in a pipeline but the last, and a command whose status is inverted with !. It notes these are the same conditions obeyed by set -e.

The script also reached end. An ERR trap reports and does not stop anything. Paired with set -e, the trap prints the line and command and the script then exits, which fires the EXIT trap, so the two work together: ERR says what broke, EXIT cleans up.

A template

#!/bin/bash
set -euo pipefail

tmp=$(mktemp)
cleanup() {
  local rc=$?
  rm -f "$tmp"
  exit "$rc"
}
trap cleanup EXIT
trap 'exit 1' INT TERM HUP
trap 'echo "error at line $LINENO: $BASH_COMMAND" >&2' ERR

Run three ways, the template exited 0 on success, 2 on a failed ls with the error line printed, and 1 on SIGTERM, and removed its temporary file every time. Each line maps to a test above: one cleanup function, status captured first and passed through, signals converted to exits so the script also behaves under sh-style shells, and an error line for the log.

Sources

  • GNU Bash Reference Manual (single-page edition), the trap builtin under “Bourne Shell Builtins”: https://www.gnu.org/software/bash/manual/bash.html

719 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *