$_ CLI In Depth
Learning progress 0%
lesson robustness traps debugging

trap & Cleanup on Exit

4 min read Module 15: Robust Scripts, Traps & Debugging Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:08

What trap does

trap ACTION SIGNAL... tells bash to run ACTION when one of the named signals or conditions occurs. ACTION is a string of shell code, and it runs in the shell that set the trap. A trap does not change how the signal is delivered to a child program. It only changes what the shell does in response to the signal or condition in its own process.

The most useful condition is the pseudo-signal EXIT. Bash runs the EXIT trap once, when the shell is about to exit, whether the script finished normally, called exit, or stopped because of a failure in strict mode. That single rule covers almost every case where cleanup matters.

A cleanup that always runs

Set the trap near the top of the script, right after you create the resource. The trap string should be simple, and it should refer to a variable that holds the path being cleaned. Quote the path inside the trap string, so that a path with spaces is removed correctly.

BASH6 lines
work=/workspace/work.d
mkdir -p "$work"
trap 'rm -rf "$work"; echo "cleaned"' EXIT
echo "working in $work"
exit 2
echo "not reached"

The output shows working in /workspace/work.d, then the exit 2 ends the script before the last echo. The trap runs on that exit as well, so the cleaned line is printed and the directory is gone. The quoting of the trap string uses single quotes so that $work is expanded when the trap runs, not when it is set.

Note

Double quotes around the trap string expand variables immediately, when trap is called. Single quotes postpone the expansion until the trap runs. Both are valid, but the choice changes the value you get if the variable changes later.

Preserving the exit status

The exit status of a script is the status of its last command, or the value passed to exit. A cleanup command that runs last can overwrite that value. If the trap runs a command that succeeds, the status of the script becomes zero, even though the script failed. Save the status at the start of the trap and exit with it at the end.

BASH1 lines
bash -c 'trap "echo bye" EXIT; exit 3'; echo "status=$?"

The output is bye followed by status=3. The trap ran, and the exit status of the script was kept. A trap that wants to change the status must end with an explicit exit, and most cleanup traps should not.

Signals and their default meanings

Signals are small messages the kernel delivers to processes. The three you will see most are INT, sent by Ctrl-C to the foreground process group, TERM, sent by kill by default, and HUP, sent when a terminal closes. A script can trap these to clean up before it stops, so that a user who presses Ctrl-C does not leave a mess behind.

BASH1 lines
bash -c 'trap "echo got TERM; exit 0" TERM; kill -TERM $$; echo "not reached"'

The script sends itself TERM, the trap prints got TERM and exits with status zero, and the final echo never runs. The $$ is the process ID of the shell, so the signal goes to the script itself. Only INT, TERM, and HUP are normal targets for cleanup; KILL cannot be trapped, because the kernel stops the process without giving it a chance to act.

Ignoring and resetting traps

An empty action, written as trap '' INT, tells the shell to ignore the signal. A dash with no action, written as trap - INT, restores the default. Use ignore only for short sections where an interruption would leave a half-finished change, and reset the trap afterward.

Hands-on: watch the EXIT trap

Run the block below and compare its output with your expectation. It registers an EXIT trap and then exits with status 4.

BASH1 lines
bash -c 'trap "echo cleanup ran" EXIT; echo working; exit 4'; echo "status=$?"

The output is working, then cleanup ran, then status=4. The lab for this unit asks you to write a script with a cleanup trap and a script that keeps its exit status, and checks both.

set -e exceptions and trap cleanup

Visualizer

set -e stops a script when a command fails, but it skips a few contexts. A trap runs cleanup on exit, and the order of EXIT, ERR and INT decides what runs when.

1 / 6
contextset -e effect
plain failing commandexits the shell
if or while conditiondoes not exit
left side of && or ||does not exit; the command after the last operator still does
command negated with !does not exit
function body, when f runs in such a contextdoes not exit

set -e ends the shell when a command fails. The rows below are the exceptions; the first row is the default rule.

bash -c 'set -e; if false; then echo no; fi; echo "after if"; false || echo "after ||"; ! false; echo "after !"; f() { false; echo "inside f"; }; f || echo "f failed"; false; echo "never printed"'
Terminal lab · 2 steps · real Linux in your browser

Clean up on every exit

Register a cleanup trap for a working directory, then keep the exit status of a script that exits with 3.

01
Remove a directory on exit
Create cleanup.sh in /workspace. It creates the directory /workspace/work.d with a file in it, registers an EXIT trap that removes the directory and prints cleaned, and then prints working: ``bash cat > cleanup.sh <<'EOF' #!/bin/bash work=/workspace/work.d mkdir -p "$work" touch "$work/note.txt" trap 'rm -rf "$work"; echo cleaned' EXIT echo working EOF `` Run it, then check that work.d no longer exists.
Show hint for step 1
The trap must be set after the directory is created, and the removal must use the quoted variable.
02
Keep the exit status
Create exit.sh in /workspace. Register a trap that prints bye on EXIT, then exit with status 3: ``bash cat > exit.sh <<'EOF' #!/bin/bash trap 'echo bye' EXIT exit 3 EOF `` Run it and check that the status is still 3 after the trap ran.
Show hint for step 2
The trap prints bye and does not change the status. The exit command at the end sets the status.
Check yourself Question 1 of 4
Concept Check When the EXIT trap runs recall

When does the action of trap ACTION EXIT run?

Recap & Key Takeaways

trap ACTION EXIT runs the action once when the shell exits, whether the script finishes, calls exit, or fails under strict mode.
Register the trap right after you create a resource, so that every later early exit still removes it.
A cleanup trap can overwrite the exit status, so save the status and exit with it when the status matters.
INT, TERM, and HUP can be trapped to clean up before stopping, but KILL cannot be trapped.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue