Traps with trap

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 123 of 205

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...
  • COMMANDS is 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.
  • CONDITION is one or more signal names or numbers, or one of Bash's special conditions: EXIT, ERR, DEBUG or RETURN.

Related forms:

CommandEffect
trap 'cmd' TERMRun cmd when the shell receives SIGTERM
trap 'cmd' INT TERMSame handler for several conditions
trap '' TERMIgnore SIGTERM completely
trap - TERMRestore the default behavior for SIGTERM
trap -pPrint the traps that are currently set
trap -lList 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 '...' KILL without an error (status 0), but neither that trap nor the EXIT trap ran when the script killed itself with kill -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:

SignalNumberTypical source
HUP1The terminal closed; by convention also "reload your configuration"
INT2The user pressed Ctrl+C
TERM15A 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 HUP handler 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/TERM handler 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 sleep runs in the background and the script waits for it, so a signal interrupts wait immediately instead of being delayed until sleep ends.
  • on_exit saves $? in its first line, before any other command changes it, and reports it. Because the script ends with exit 0 after 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Traps with trap and get answers drawn from it.

Signed-in readers only.