Handling Interrupts and Termination Signals

Su Suriya Ravichandran Updated 06 Dec 2026
17 min read ·Lesson 141 of 205

A running script can be asked to stop at any moment. The user presses Ctrl + C, a service manager sends SIGTERM during a shutdown, or the terminal window is closed and the script receives SIGHUP. If the script does nothing about it, Bash applies the default action of the signal and the script ends immediately, in the middle of whatever it was doing: a temporary file stays behind, a half-written output file is left on disk, or a job is recorded as neither done nor pending.

Handling these signals means deciding, for each one, what the script should do instead: clean up and exit, finish the current unit of work first, or ignore the signal during a short critical section. The tool for this is trap (lesson 123), and lesson 140 showed the sending side with kill. This lesson covers the receiving side in practice: which signals mean "please stop", how Ctrl + C actually reaches a script and its child processes, when Bash runs a handler, and how a script should end so that its caller sees what happened.

The Signals That Mean "Stop"

SignalNumberUsually sent byDefault action
SIGINT2Ctrl + C in the terminalterminate
SIGTERM15kill PID, systemctl stop, docker stop, a shutdownterminate
SIGHUP1the terminal closing, an SSH connection droppingterminate
SIGQUIT3Ctrl + \ in the terminalterminate with core dump
SIGKILL9kill -9, the kernel when memory runs outterminate; cannot be handled

The first four can be trapped. SIGKILL cannot: no handler runs, and the script cannot clean up. This is why well-behaved tools send SIGTERM first and use SIGKILL only after a timeout (lesson 140 built a script that does exactly that).

When a process ends because of a signal, its exit status is 128 plus the signal number: 130 for SIGINT, 143 for SIGTERM, 129 for SIGHUP, 137 for SIGKILL.

What Happens Without a Handler

A script that does not handle Ctrl + C simply ends. This script was run from an interactive Bash in a terminal, and Ctrl + C was pressed half a second after it started:

# plain.sh
echo "plain: working"
sleep 5
echo "plain: this line is not reached"
$ bash plain.sh
plain: working
^C
$ echo "status $?"
status 130

The terminal echoes ^C when the key is pressed. The status 130 tells the interactive shell that the script was ended by SIGINT. If the script had created temporary files, they would still exist.

How Ctrl + C Reaches a Script

Ctrl + C is not sent to "the script". The terminal driver sends SIGINT to every process in the foreground process group of the terminal (lesson 135). When an interactive Bash starts bash plain.sh, the script and every command it runs in the foreground, here sleep 5, belong to that group. All of them receive SIGINT at the same moment.

This explains two things you will see in the examples below:

  • When the script has a handler for SIGINT, the foreground command it was running (sleep) is usually still killed by the same Ctrl + C, because sleep has no handler of its own.
  • A signal sent with kill PID reaches only the process with that PID. A script that receives SIGTERM from kill may still have a child running that knows nothing about it.

Cleaning Up and Exiting

The most common handler removes what the script created and then exits:

# cleanup.sh
tmp=$(mktemp)
on_int() {
  echo
  echo "cleanup: interrupted, removing $tmp"
  rm -f "$tmp"
  exit 130
}
trap on_int INT
echo "cleanup: working with $tmp"
sleep 5
rm -f "$tmp"
echo "cleanup: done"
$ bash cleanup.sh
cleanup: working with /tmp/tmp.hMp5N0DDaI
^C
cleanup: interrupted, removing /tmp/tmp.hMp5N0DDaI
$ echo "status $?"
status 130

The echo with no arguments at the start of the handler moves the message to a new line after the ^C. The handler ends with exit 130, the conventional status for "interrupted". Without an exit, the script would continue after the interrupted command, which is the next behavior to look at.

For cleanup that must happen however the script ends, an EXIT trap is usually simpler (lesson 124): Bash runs it on a normal end, on exit, and also when the script is ended by SIGINT, SIGTERM or SIGHUP. A script with only an EXIT trap, ended with kill -TERM:

# exittrap.sh
trap 'echo "exittrap.sh: EXIT trap ran"' EXIT
sleep 5 & wait $!
exittrap.sh: EXIT trap ran
status 143

The script still ended with the default action of SIGTERM (status 143), but the cleanup ran first.

A Handler That Does Not Exit

When the handler returns without calling exit, the script continues with the command after the one that was interrupted:

# cont.sh
trap 'echo " (Ctrl+C ignored for step $step)"' INT
for step in 1 2 3; do
  echo "step $step"
  sleep 1
done
echo "all steps done"
$ bash cont.sh
step 1
^C (Ctrl+C ignored for step 1)
step 2
step 3
all steps done
$ echo "status $?"
status 0

The script survived the signal, but sleep 1 of step 1 did not: it was in the same foreground process group and ended at once. The loop then moved on to step 2. This is a property of every foreground command: a handler in the script protects the script, not the programs it runs.

When Bash Runs the Handler

A detail of Bash matters a great deal for SIGTERM: while Bash waits for a foreground command to finish, it does not run a trap handler. The handler runs after the command ends. The signal is remembered, not lost, but the response is delayed.

Two scripts show the difference. Both run a 3-second sleep and handle SIGTERM; the first runs sleep in the foreground, the second in the background followed by wait:

# fg.sh
trap 'echo "fg.sh: TERM received, exiting"; exit 143' TERM
echo "fg.sh: running sleep 3 in the foreground"
sleep 3
echo "fg.sh: sleep finished"
# bgwait.sh
child=
on_term() {
  echo "bgwait.sh: TERM received, stopping child $child"
  kill "$child" 2>/dev/null
  wait "$child"
  exit 143
}
trap on_term TERM
echo "bgwait.sh: running sleep 3 in the background"
sleep 3 & child=$!
wait "$child"
echo "bgwait.sh: sleep finished"

Each script was started in the background, sent SIGTERM after half a second, and timed while its parent waited for it:

TIMEFORMAT='took %1Rs'
bash fg.sh & p=$!
sleep 0.5; kill -TERM "$p"
time wait "$p"; echo "status $?"
echo ---
bash bgwait.sh & p=$!
sleep 0.5; kill -TERM "$p"
time wait "$p"; echo "status $?"
sleep 0.1; echo "sleep 3 processes left: $(pgrep -xc sleep -r S,R)"
fg.sh: running sleep 3 in the foreground
fg.sh: TERM received, exiting
took 2.5s
status 143
---
bgwait.sh: running sleep 3 in the background
bgwait.sh: TERM received, stopping child 343
took 0.0s
status 143
sleep 3 processes left: 0

fg.sh received the signal after 0.5 seconds but answered only when sleep 3 had finished, 2.5 seconds later. A script that runs a long foreground command, such as a backup or a download, can therefore appear to ignore SIGTERM for minutes, and a service manager may lose patience and send SIGKILL.

bgwait.sh reacted immediately. The built-in wait is interrupted by a trapped signal: it returns at once with a status above 128, the handler runs, and the handler can stop the child itself. Because kill reached only the script, the handler must pass the signal on to the child, which is what kill "$child" does. The last line confirms that no sleep process was left running.

The pattern command & wait $! is the standard way to make a script responsive to signals while it runs a long command.

How the Caller Sees an Interrupt

The exit status is not the only way a parent process learns what happened to a child. The operating system also reports whether the child ended because of a signal. Bash uses this when it runs a loop or a list of commands in a script and the user presses Ctrl + C:

  • If the child was killed by SIGINT, Bash assumes the user wants to stop everything, and the calling script stops too.
  • If the child exited normally after handling SIGINT, even with exit 130, Bash assumes the child dealt with the interrupt on purpose, and the calling script continues.

Two versions of a small script show this. One exits with status 130; the other resets its trap and sends SIGINT to itself, so that it really ends by the signal:

# exit130.sh
trap 'echo " exit130.sh $1: cleaned up"; exit 130' INT
sleep 2
# reraise.sh
trap 'echo " reraise.sh $1: cleaned up"; trap - INT; kill -INT $$' INT
sleep 2

A loop runs one of them three times:

# loop.sh
for i in 1 2 3; do
  echo "loop: run $i"
  bash "$1" "$i"
done
echo "loop: finished"

Ctrl + C was pressed during the first run in both cases:

$ bash loop.sh exit130.sh
loop: run 1
^C exit130.sh 1: cleaned up
loop: run 2
loop: run 3
loop: finished
$ echo "status $?"
status 0
$ bash loop.sh reraise.sh
loop: run 1
^C reraise.sh 1: cleaned up

$ echo "status $?"
status 130

With exit 130, the loop carried on as if nothing had happened, and the user had to press Ctrl + C again for every remaining run. With the re-raised signal, the loop stopped as the user intended, and the interactive shell received status 130.

So a script that handles SIGINT only to clean up should end by re-raising the signal:

trap - INT          # restore the default action
kill -INT $$        # send the signal to this script again

The same applies to SIGTERM and SIGHUP. trap - SIGNAL is necessary, because otherwise the script's own handler would catch the signal a second time.

Ignoring a Signal for a Short Time

trap '' SIGNAL, with an empty string as the action, tells the system to ignore the signal. This protects a short critical section, such as writing several related files that must stay consistent. trap - SIGNAL restores the default afterwards:

# critical.sh
echo "critical.sh: starting update"
trap '' INT                 # ignore Ctrl+C during the critical section
for part in 1 2 3; do
  echo "  writing part $part"; sleep 0.5
done
trap - INT                  # back to the default action
echo "critical.sh: update complete, now waiting"
sleep 3
echo "critical.sh: not reached when interrupted"

Ctrl + C was pressed twice during the update and once afterwards:

$ bash critical.sh
critical.sh: starting update
  writing part 1
^C  writing part 2
^C  writing part 3
critical.sh: update complete, now waiting
^C
$ echo "status $?"
status 130

The two early presses had no effect on the script or on the sleep commands, because an ignored signal is inherited by child processes: the commands started during the critical section ignored SIGINT too. The third press, after trap - INT, ended the script normally.

Two limits apply. An ignored signal is discarded, not postponed: the two early presses were simply lost. The complete example below remembers the request in a variable instead, which is usually friendlier. And a critical section should stay short; a script that ignores Ctrl + C for minutes frustrates its user.

Signals Ignored at Startup Cannot Be Trapped

A non-interactive Bash cannot handle a signal that was already ignored when it started. trap accepts the command, but the signal stays ignored:

# entry.sh
trap 'echo "entry.sh: got INT"' INT
echo "entry.sh trap list: [$(trap -p INT)]"
kill -INT $$
echo "entry.sh: still running"
echo "normal start:"
bash entry.sh
echo "status $?"
echo "started with INT ignored:"
trap '' INT
bash entry.sh
echo "status $?"
normal start:
entry.sh trap list: [trap -- 'echo "entry.sh: got INT"' SIGINT]
entry.sh: got INT
entry.sh: still running
status 0
started with INT ignored:
entry.sh trap list: [trap -- '' SIGINT]
entry.sh: still running
status 0

In the second run, trap -p still shows the inherited empty action, and the handler never runs. This rule exists so that a parent that deliberately ignores a signal, such as nohup with SIGHUP, can rely on its children ignoring it too.

Signals and Background Jobs

In a script without job control, Bash starts a simple command run with & with SIGINT and SIGQUIT ignored, so Ctrl + C does not reach it. This is not true for everything put in the background: in tests with Bash 5.2, a function, a { ...; } group or a ( ... ) subshell started with & ran its own commands with the default action for SIGINT, so Ctrl + C ended them even though they were "in the background".

When a background job must survive Ctrl + C, say so explicitly inside it:

( trap '' INT; process_job "$job" ) &

The ignored disposition is inherited by every command the subshell starts. SIGTERM sent with kill to the script is not affected, because it reaches only the script anyway.

A Complete Example: Finishing the Current Job Before Stopping

worker.sh processes a queue of job files. A stop request, from Ctrl + C, kill (SIGTERM) or a lost terminal (SIGHUP), does not interrupt the job in progress: the worker finishes it, leaves the remaining jobs untouched for the next run, and stops. A second stop request means "now": the current job is abandoned. The worker always ends with the real signal, so its caller sees the interrupt.

#!/usr/bin/env bash
# worker.sh QUEUE_DIR: process each *.job file in QUEUE_DIR, in name order.
# Ctrl+C, SIGTERM or SIGHUP: finish the current job, then stop.
# A second signal: abandon the current job and stop at once.
set -uo pipefail
queue=${1:?usage: worker.sh QUEUE_DIR}
[[ -d $queue ]] || { echo "worker: $queue: not a directory" >&2; exit 2; }

work=$(mktemp -d) || exit 1
trap 'rm -rf "$work"' EXIT

stop_signal=   # name of the first stop signal received
job_pid=       # PID of the running job, if any

request_stop() {
  local sig=$1
  if [[ -n $stop_signal ]]; then
    echo "worker: second $sig, abandoning the current job" >&2
    # end the job subshell and the commands it started (pgrep is from procps)
    [[ -n $job_pid ]] && kill -TERM $(pgrep -P "$job_pid") "$job_pid" 2>/dev/null
    trap - "$sig"
    kill -s "$sig" $$          # end with the real signal status
  fi
  stop_signal=$sig
  echo "worker: $sig received, finishing the current job first" >&2
}
for sig in INT TERM HUP; do
  trap "request_stop $sig" "$sig"
done

# A job file holds a number of seconds; the job "works" that long
# and writes a result file.
process_job() {
  local seconds
  read -r seconds < "$1"
  sleep "$seconds"
  echo "processed in ${seconds}s" > "$work/result"
  mv "$work/result" "${1%.job}.out"
}

for job in "$queue"/*.job; do
  [[ -e $job ]] || continue
  [[ -n $stop_signal ]] && break
  echo "worker: starting ${job##*/}"
  ( trap '' INT; process_job "$job" ) &   # the job itself ignores Ctrl+C
  job_pid=$!
  while kill -0 "$job_pid" 2>/dev/null; do
    wait "$job_pid"      # returns early when a trapped signal arrives
  done
  wait "$job_pid"; rc=$? # the job has ended: its real exit status
  job_pid=
  if (( rc == 0 )); then
    mv "$job" "$job.done"
    echo "worker: finished ${job##*/}"
  else
    echo "worker: ${job##*/} failed with status $rc" >&2
  fi
done

if [[ -n $stop_signal ]]; then
  echo "worker: stopped early; $(ls "$queue" | grep -c '\.job$') job(s) left" >&2
  trap - "$stop_signal"
  kill -s "$stop_signal" $$
fi
echo "worker: queue empty"

How It Works

  • One handler, three signals. The loop for sig in INT TERM HUP installs request_stop INT, request_stop TERM and request_stop HUP. The handler receives the signal name, so it can re-raise the same signal later.
  • A flag instead of an exit. The first signal only sets stop_signal. The main loop checks the flag before it starts each job, so a stop request is never lost and never interrupts a job halfway.
  • The job ignores Ctrl + C. Ctrl + C goes to the whole foreground process group, which includes the job. ( trap '' INT; process_job "$job" ) & makes the job and its sleep ignore SIGINT. A first draft without this line was tested: the same Ctrl + C ended the job at once, and the worker reported a.job failed with status 130.
  • A responsive wait. wait "$job_pid" returns as soon as a trapped signal arrives, so the handler runs immediately rather than after the job. The while kill -0 loop then waits again until the job has really ended, and the final wait "$job_pid" returns the job's remembered exit status (lesson 138).
  • The second signal kills the job subshell and its children. pgrep -P lists the children of the subshell; without it, an earlier version killed only the subshell and left its sleep running as an orphan.
  • Ending with the signal. Both the abandon path and the normal "stopped early" path reset the trap and send the signal to $$, so the status is 130, 143 or 129 and a calling loop stops. The EXIT trap removes the temporary folder in every case.
  • Results appear atomically. The job writes its result in the temporary folder and moves it into place with mv. The .job file is renamed to .job.done only after the job succeeded, so an interrupted run leaves the queue in a state the next run can continue from.

Running the Complete Example

Each test used a fresh queue folder q with three jobs of 2 seconds each: a.job, b.job and c.job. Without any signal, all three ran:

$ bash worker.sh q
worker: starting a.job
worker: finished a.job
worker: starting b.job
worker: finished b.job
worker: starting c.job
worker: finished c.job
worker: queue empty
$ echo "status $?"; ls q
status 0
a.job.done  a.out  b.job.done  b.out  c.job.done  c.out

Ctrl + C pressed once, during the first job:

$ bash worker.sh q
worker: starting a.job
^Cworker: INT received, finishing the current job first
worker: finished a.job
worker: stopped early; 2 job(s) left

$ echo "status $?"; ls q
status 130
a.job.done  a.out  b.job  c.job

The first job completed normally, the other two were left for the next run, and the status was 130. The empty line before the prompt is printed by the interactive Bash when a foreground command ends by SIGINT.

Ctrl + C pressed twice:

$ bash worker.sh q
worker: starting a.job
^Cworker: INT received, finishing the current job first
^Cworker: second INT, abandoning the current job

$ echo "status $?"; ls q; pgrep -xc sleep
status 130
a.job  b.job  c.job
0

The job was abandoned, so a.job was not marked as done, and no sleep process was left behind.

The same worker was also stopped by signals from another script, which started it with bash worker.sh q &:

bash worker.sh q & w=$!
sleep 0.5; kill -TERM $w
wait $w; echo "after TERM: status $? ($(kill -l $?))"; ls q
worker: starting a.job
worker: TERM received, finishing the current job first
worker: finished a.job
worker: stopped early; 2 job(s) left
after TERM: status 143 (TERM)
a.job.done
a.out
b.job
c.job

Two SIGHUP signals sent 0.3 seconds apart:

worker: starting a.job
worker: HUP received, finishing the current job first
worker: second HUP, abandoning the current job
t3.sh: line 10:   616 Hangup                  bash worker.sh q
after two HUPs: status 129 (HUP)
a.job
b.job
c.job
sleep processes left: 0

The Hangup line comes from the calling script's Bash, which reports a background job that was ended by a signal. A missing queue folder is rejected with status 2, and a call without arguments stops with the ${1:?} message and status 1:

worker: missing: not a directory
status 2
worker.sh: line 6: 1: usage: worker.sh QUEUE_DIR
status 1

After all of these runs, no temporary folder from mktemp -d remained in /tmp.

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 Handling Interrupts and Termination Signals and get answers drawn from it.

Signed-in readers only.