Traps with trap
The trap builtin tells Bash to run a command when something specific happens to the shell: the script is about to exit, a signal arrives from outside, or a command fails. Without traps, a script has no say in how it ends. If someone presses Ctrl+C, if a service manager sends a termination signal, or if set -e stops the script on an error, execution simply stops wherever it was. With a trap, the script gets a chance to react first: to remove temporary files, print where it failed, save its progress, or ignore a signal it should not die from.
Syntax
trap 'COMMANDS' CONDITION...
COMMANDSis a string that Bash stores and runs later, when one of the conditions occurs. It can be any shell code, but it is usually a short command or the name of a function.CONDITIONis one or more signal names or numbers, or one of Bash's special conditions:EXIT,ERR,DEBUGorRETURN.
Related forms:
| Command | Effect |
|---|---|
trap 'cmd' TERM | Run cmd when the shell receives SIGTERM |
trap 'cmd' INT TERM | Same handler for several conditions |
trap '' TERM | Ignore SIGTERM completely |
trap - TERM | Restore the default behavior for SIGTERM |
trap -p | Print the traps that are currently set |
trap -l | List signal names and numbers |
Signal names can be written with or without the SIG prefix, or as numbers: TERM, SIGTERM and 15 all mean the same signal. An unknown name is an error:
trap "echo x" BOGUS
bash: line 1: trap: BOGUS: invalid signal specification
The first lines of trap -l show the numbering used on Linux:
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
The EXIT Trap
EXIT is not a real signal. It is a condition Bash defines for "the shell is about to exit", whatever the reason. It is the trap most scripts need, because it covers every way a script can end in one place:
trap 'echo "EXIT trap ran"' EXIT
echo "script body"
script body
EXIT trap ran
The trap runs after the last line of the script. It also runs when the script calls exit, and at the start of the trap $? holds the status the script is exiting with:
trap 'echo "leaving with status $?"' EXIT
echo working
exit 3
working
leaving with status 3
The script's own status stayed 3. An EXIT trap does not change the exit status unless it calls exit itself.
It runs when set -e stops the script, too:
set -e
trap 'echo "leaving with status $?"' EXIT
ls /nonexistent
echo "not reached"
ls: cannot access '/nonexistent': No such file or directory
leaving with status 2
EXIT When a Signal Ends the Script
In Bash, the EXIT trap also runs when a signal such as SIGTERM or SIGINT ends the script, even if there is no trap for that signal. This script was started in the background and sent SIGTERM while it waited:
trap 'echo "EXIT trap ran"' EXIT
sleep 5 &
wait
echo "not reached"
EXIT trap ran
The script's status was 143 (128 + 15, lesson 116). Sending SIGINT to itself with kill -INT $$ gave the same result with status 130.
Two exceptions are important:
- SIGKILL cannot be caught. The kernel ends the process immediately. Bash accepted
trap '...' KILLwithout an error (status 0), but neither that trap nor the EXIT trap ran when the script killed itself withkill -KILL $$; the script just ended with status 137. SIGSTOP cannot be caught either. - Other shells differ. Dash 0.5.12 did not run its EXIT trap when the same script was ended by SIGTERM. A portable script, or one that must clean up reliably in any shell, adds explicit traps for INT and TERM that call
exit(lesson 124 shows this pattern).
Trapping Signals
A signal is a small notification that the operating system delivers to a process (lessons 140-141 cover signals in depth). The common ones a script deals with:
| Signal | Number | Typical source |
|---|---|---|
HUP | 1 | The terminal closed; by convention also "reload your configuration" |
INT | 2 | The user pressed Ctrl+C |
TERM | 15 | A polite request to stop: kill PID, a service manager, timeout |
A trap replaces the default action, which for these three is to end the process. After the handler runs, the script continues where it was:
trap 'echo "caught INT"' INT
trap 'echo "caught TERM"' TERM
kill -INT $$
kill -TERM $$
echo "script continues after handling both"
caught INT
caught TERM
script continues after handling both
The script ended with status 0. This is often not what you want for INT and TERM: the user pressed Ctrl+C to stop the script, not to make it print a message and carry on. A handler for these signals normally ends with exit and the conventional status:
trap 'echo "interrupted, cleaning up" >&2; exit 130' INT
echo "working"
kill -INT $$
echo "not reached"
working
interrupted, cleaning up
The script ended with status 130 (128 + 2), so a calling script or a CI system can see that it was interrupted rather than finished.
Ignoring a Signal
An empty string as the command makes the shell ignore the signal:
trap '' TERM
kill -TERM $$
echo "TERM was ignored"
TERM was ignored
Ignoring is inherited by child processes, so commands started from the script ignore the signal too. Use it sparingly, for short sections that must not be interrupted halfway, and restore the default afterwards with trap - TERM.
When Does a Trap Run?
Bash does not interrupt a running foreground command to run a trap. It records the signal and runs the handler when the current command finishes. This script was sent SIGTERM half a second after it started a three-second sleep:
trap 'echo "TERM handled at $(date +%s)"' TERM
start=$(date +%s)
echo "start $start"
sleep 3
echo "sleep finished at $(date +%s)"
start 1795330604
TERM handled at 1795330607
sleep finished at 1795330607
The handler ran three seconds after the start, when sleep ended, not at the moment the signal arrived. With a long-running command, a script can seem to ignore a signal for a long time.
The wait builtin is different: a trapped signal interrupts it immediately. Running the slow command in the background and waiting for it lets the handler run without delay:
trap 'echo "TERM handled after $((SECONDS)) s"' TERM
sleep 3 &
wait $!
echo "wait returned status $? after $SECONDS s"
Sent SIGTERM after one second:
TERM handled after 1 s
wait returned status 143 after 1 s
wait returned a status greater than 128 to show it was interrupted by a signal. The background sleep was still running at that point; lesson 124 shows how to stop such processes in cleanup code.
Quoting the Trap Command
The trap string is stored and evaluated when the trap runs, so the choice of quotes decides when variables are expanded:
name=first
trap "echo double quotes: name=$name" EXIT
name=second
double quotes: name=first
name=first
trap 'echo single quotes: name=$name' EXIT
name=second
single quotes: name=second
With double quotes, $name was replaced when trap was set, so the stored command was echo double quotes: name=first. With single quotes, the stored command still contains $name, which is expanded when the trap runs. Single quotes are the usual choice: the trap should see the current values at exit time, such as the name of a temporary file created after the trap was set. Using a function as the handler sidesteps the question entirely, because the function body is evaluated when it is called:
on_exit() { echo "cleaning up $tmpfile"; }
trap on_exit EXIT
One Handler per Condition
Setting a trap replaces any previous trap for the same condition:
trap 'echo one' EXIT
trap 'echo two' EXIT
two
trap -p shows what is currently set, in a form that could be pasted back into the shell, and trap - removes a trap:
trap 'echo bye' EXIT
trap 'echo got TERM' TERM
trap -p
trap - TERM
echo "after reset:"
trap -p
trap -- 'echo bye' EXIT
trap -- 'echo got TERM' SIGTERM
after reset:
trap -- 'echo bye' EXIT
Because each condition has a single handler, scripts that need several cleanup steps put them all in one function and set the trap once. Adding pieces to an existing trap by parsing the output of trap -p is possible but fragile, because the stored text has its own quoting.
Scope: Functions, Subshells and Command Substitution
Traps belong to the shell process, not to the function that sets them. A trap set inside a function stays in effect after the function returns:
setup() { trap 'echo "cleanup from setup"' EXIT; }
setup
echo "main continues"
main continues
cleanup from setup
A subshell, on the other hand, does not run the parent's traps. This script set an EXIT trap and then started two subshells:
trap 'echo "EXIT trap in PID $BASHPID"' EXIT
( echo "in subshell $BASHPID"; trap -p )
x=$(trap -p EXIT)
echo "trap -p inside \$( ): [$x]"
( trap 'echo "subshell own EXIT trap"' EXIT; echo "subshell body" )
echo "main body $BASHPID"
in subshell 502
trap -- 'echo "EXIT trap in PID $BASHPID"' EXIT
trap -p inside $( ): [trap -- 'echo "EXIT trap in PID $BASHPID"' EXIT]
subshell body
subshell own EXIT trap
main body 501
EXIT trap in PID 501
Three things are visible here. trap -p inside a subshell still displays the parent's traps (Bash does this on purpose, so that x=$(trap -p) can save them), but the first subshell ended without running them. A subshell can set its own trap, which runs when that subshell ends. And the parent's EXIT trap ran exactly once, in the main shell (PID 501). Ignored signals (trap '') are the exception: they stay ignored in subshells and child processes.
The ERR Trap
The ERR condition runs its command whenever a command fails, using the same rules as set -e (lesson 119). Failures in if conditions, on the left side of || or &&, and after ! do not trigger it:
trap 'echo "ERR: line $LINENO: $BASH_COMMAND -> $?"' ERR
false
grep -q x /nonexistent 2>/dev/null
if false; then :; fi
false || true
echo "after"
ERR: line 2: false -> 1
ERR: line 3: grep -q x /nonexistent 2> /dev/null -> 2
after
Inside the trap, $LINENO is the line of the failing command, $BASH_COMMAND is the command as Bash re-printed it, and $? is its status. Without set -e the script continues after the trap runs; with set -e the trap runs first and then the script stops. As lesson 121 showed, the ERR trap is not inherited by functions, command substitutions or subshells unless set -E (errtrace) is on. ERR is a Bash feature; Dash rejected it with trap: ERR: bad trap.
DEBUG and RETURN
Two more Bash-specific conditions are used mainly for debugging and tracing. DEBUG runs before every simple command:
trap 'echo "about to run: $BASH_COMMAND"' DEBUG
x=5
echo "x=$x"
trap - DEBUG
about to run: x=5
about to run: echo "x=$x"
x=5
about to run: trap - DEBUG
RETURN runs when a function, or a file loaded with source, finishes. Like ERR, these traps are not inherited by functions by default. A RETURN trap set at the top level did not run when a function returned until set -T (functrace) was enabled:
set -T
f() { echo "in f"; }
trap 'echo "RETURN trap: function returned"' RETURN
f
in f
RETURN trap: function returned
Lessons 126 and 184 cover tracing with bash -x, which is the more common tool for following a script's execution.
A Complete Example
This worker script repeats a task until it is told to stop. It uses three traps, each for a different purpose: HUP reloads the settings without stopping, INT and TERM request a clean stop, and EXIT prints a final report however the script ends.
#!/usr/bin/env bash
# worker.sh: run a task repeatedly; HUP reloads settings, INT/TERM stop cleanly
conf=worker.conf
interval=1
runs=0
stop=0
load_config() {
if [[ -r $conf ]]; then
interval=$(sed -n 's/^interval=//p' "$conf")
fi
echo "config loaded: interval=$interval"
}
on_exit() {
local rc=$?
echo "worker stopped after $runs runs (status $rc)"
}
trap load_config HUP
trap 'echo "stop requested"; stop=1' INT TERM
trap on_exit EXIT
load_config
echo "worker started, PID $$"
while (( ! stop )); do
runs=$((runs + 1))
sleep "$interval" &
wait $!
done
exit 0
The test started the worker with interval=0.5 in worker.conf, changed the file to interval=0.2 after about a second and sent SIGHUP, then sent SIGTERM a second later:
printf 'interval=0.5\n' > worker.conf
./worker.sh & p=$!
sleep 1.2; printf 'interval=0.2\n' > worker.conf; kill -HUP "$p"
sleep 1; kill -TERM "$p"; wait "$p"; echo "status $?"
config loaded: interval=0.5
worker started, PID 542
config loaded: interval=0.2
stop requested
worker stopped after 8 runs (status 0)
status 0
The number of runs depends on timing and will differ between runs. How it works:
- The
HUPhandler is a function, so it reads the configuration file as it is at the moment the signal arrives. After it returns, the loop continues with the new interval. - The
INT/TERMhandler does not exit immediately; it sets a flag. The loop finishes its current step and then ends normally, so the work is never cut off halfway. The same pattern can save state or finish writing a file before stopping. - Each
sleepruns in the background and the script waits for it, so a signal interruptswaitimmediately instead of being delayed untilsleepends. on_exitsaves$?in its first line, before any other command changes it, and reports it. Because the script ends withexit 0after a requested stop, the status is 0: stopping on request is a success for this program.
The examples were run with Bash 5.2.21, Dash 0.5.12, GNU sed 4.9 and GNU coreutils 9.4 on Ubuntu 24.04. Process IDs and timestamps differ on every run.