Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 95 ยท Shell Scripting

Signals and trap

Understand Unix signals and the Bash trap builtin: INT, TERM, HUP, USR1, EXIT, cleanup handlers, kill to $$, ignoring signals, background jobs and wait statuses.

A signal is a tiny message the kernel (or another process) sends to a running process: "the user pressed Ctrl-C", "please shut down", "your terminal went away", "do the thing you do on USR1". A process can usually decide what to do when one arrives, and in Bash the tool for that decision is the builtin trap.

In this lesson you will learn which signals matter in scripts, how to run a handler when one arrives, how to clean up reliably with the pseudo-signal EXIT, how to send signals with kill (even to your own script, using $$), how to ignore signals, and what happens to background jobs and their exit statuses. It builds on Exit Codes, set -e and Error Handling; the next section of the course covers the command-line side in kill, Signals and Process Control.

What signals are

Each signal has a name and a number. Ask Bash for the list with kill -l:

Bash The signals you will actually meet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The table below describes the ones you will use most.

Signal Number Typical cause Default action
SIGHUP 1 Terminal closed; also "reload your config" for daemons Terminate
SIGINT 2 You press Ctrl-C Terminate
SIGQUIT 3 You press Ctrl-\ Terminate and dump core
SIGKILL 9 kill -9: cannot be caught or ignored Terminate
SIGUSR1, SIGUSR2 10, 12 Free for programs to define Terminate
SIGPIPE 13 Writing to a pipe nobody reads Terminate
SIGTERM 15 Plain kill pid: "please stop" Terminate
SIGCHLD 17 A child process ended Ignored

The numbers are those of Linux on x86 and ARM; a few (like USR1) differ on other systems, so use names in scripts. When a process dies from a signal, its exit status is 128 plus the signal number, which is why Ctrl-C shows up as 130 and kill (SIGTERM) as 143.

trap: running code when a signal arrives

The syntax is:

TEXT
trap 'commands' SIGNAL [SIGNAL ...]     # run commands when SIGNAL arrives
trap '' SIGNAL                          # ignore SIGNAL
trap - SIGNAL                           # restore the default action
trap -p                                 # list current traps

Put the commands in single quotes, so that variables are expanded when the trap fires, not when you set it. Simplest way to try it without waiting for a human to press Ctrl-C: let the script send the signal to itself with kill -s SIGNAL $$, where $$ is the PID of the running shell.

Bash A script that signals itself

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The last line shows two facts at once. With no trap, TERM uses its default action and ends the process, and the status reported to the caller is 143, which is 128 + 15. Notice also that the handlers ran between the commands: Bash runs a trap after the current foreground command finishes. If your script is sitting in a long sleep 60, the trap does not run until sleep returns, unless the sleep is a background job you wait for (more below).

The EXIT pseudo-signal

EXIT is not a real signal; it is a hook Bash runs whenever the shell is about to exit, no matter why: reaching the end of the script, an exit command, a failing command under set -e, or a trapped signal that ends the script. That makes it the right place for cleanup.

Bash EXIT runs on every way out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

In every case the EXIT trap ran exactly once. For end, exit and error, $? inside the trap is the status the shell is about to exit with. The term case is different: the script has no TERM trap, so the signal kills it, yet Bash still runs the EXIT trap on the way out (inside it $? is 0 here, while the caller sees 143). A kill -9 (SIGKILL) would skip the trap entirely, since nothing can intercept that signal.

A reliable cleanup pattern

Combine EXIT with a function and put the trap right after you create the resource:

Terminal
tmp=$(mktemp -d)
trap 'rm -rf -- "$tmp"' EXIT

Because of the single quotes, $tmp is expanded when the trap runs, so even if you reassign it later, the handler sees the current value. Setting a trap twice for the same signal replaces the first one; if you need several cleanup steps, put them in one function and call that.

Handling INT and TERM: stop gracefully

When the user hits Ctrl-C, a well-behaved script should stop, clean up, and report that it was interrupted, with the conventional status 130. The usual trick is a handler that exits; EXIT then does the cleanup.

Bash A graceful shutdown on TERM and INT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The loop stopped at tick 2, the INT handler exited with 130, and the EXIT trap removed the lock file. Note the division of work: the signal handler decides how to exit, EXIT does the cleanup, so cleanup runs exactly once whatever path led there.

A handler that does not call exit makes the script continue after the signal. That is what you want for USR1 ("print status") but not for INT or TERM: an INT trap that only prints a message turns Ctrl-C into a harmless no-op and users will have to find the process and kill -9 it.

Ignoring signals

An empty trap tells the shell to ignore the signal. This is useful for a critical section that must not be torn in half (updating two files that belong together), but keep it short.

Bash Ignoring INT for a critical section

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

One subtle rule: signals that were ignored when the shell started (for example by nohup or a parent that ran trap '' HUP) cannot be un-ignored by a script. And an ignored signal is inherited by programs you start, while a trapped signal is reset to its default in them, because a handler lives in your shell's memory and cannot exist in another program.

Signals and background jobs

Put & after a command and it runs in the background; its PID is in $!. wait PID waits for that child to finish and returns its exit status, so you can learn whether it succeeded, or whether it was killed (128 + signal).

Bash Starting, signalling and waiting for children

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The job order of the "job N done" lines is decided by the scheduler, so on a real machine they may come out in any order; here they ran fast enough to print in order, but do not rely on that.

Cleaning up children when the script is stopped

If the parent script dies, its background children keep running (orphans). A script that starts helpers should kill them on exit. Use trap plus jobs -p, which prints the PIDs of the shell's background jobs.

Bash Stopping helper processes on exit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Without the trap, those two sleep 30 processes would keep running after the script ended. $pids is deliberately unquoted so the shell splits it into separate PIDs (the only legitimate use of an unquoted variable in this lesson).

Using USR1 as a control channel

Long-running programs often use USR1 or HUP as a lightweight remote control: "print your status" or "reload your configuration". A trap handler that returns normally lets the script continue.

Bash USR1 to ask a loop for its status

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The sleep 0.1 & wait $! pattern matters. A trap handler cannot interrupt a foreground command, but it can interrupt the builtin wait: Bash runs the handler immediately and wait returns with status 128 + the signal number. In loops that must react quickly to signals, wait for the background sleep instead of sleeping in the foreground.

Pitfalls and good habits

  • Quote the trap command with single quotes so variables are read when the trap runs.
  • Use signal names, not numbers: trap cleanup TERM, not trap cleanup 15.
  • Keep handlers short and safe. A handler may run at any point between two commands, even while you are halfway through updating your variables. Set a flag (stop=1) and check it in the loop if the work is complex.
  • Do not rely on kill -9. Try TERM first, wait a little, and only then use KILL.
  • Subshells: a subshell ( ... ) resets caught signals to their default and does not run the parent's EXIT trap, and ERR is only inherited with set -E. Set traps again inside the subshell if it needs them.
  • set -e and traps: an ERR trap and an EXIT trap work together; see Exit Codes, set -e and Error Handling.
  • Process basics: PIDs, parents and /proc are explained in Processes, job control in Jobs and Background Processes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A script is killed with a plain kill PID and has no TERM trap. What exit status does its parent see?

    A process terminated by a signal reports 128 plus the signal number. SIGTERM is 15, so the status is 143. Status 130 is SIGINT (Ctrl-C), 128 + 2.
  2. 2. Which of these runs a cleanup function when the script ends normally, fails, or is stopped by SIGTERM?

    EXIT fires whenever the shell exits, for any reason that Bash can observe. ERR only fires on failing commands, and KILL cannot be trapped at all.
  3. 3. Why should the command of a trap normally be written in single quotes, such as trap 'rm -rf "$tmp"' EXIT?

    Inside single quotes nothing is expanded when you define the trap. The text is evaluated at the moment the signal arrives, so it sees the current value of the variable.
  4. 4. Your INT handler only prints a message and does not call exit. What happens when the user presses Ctrl-C?

    Trapping a signal replaces its default action. If the handler returns, execution resumes where it left off, so Ctrl-C no longer stops the script unless the handler calls exit.
  5. 5. What does wait $pid return for a background job that was stopped with SIGKILL?

    wait reports the child's exit status. For a child killed by signal 9 that is 128 + 9 = 137.

Summary

  • Signals are small messages to a process; a death by signal N reports status 128 + N (130 for INT, 143 for TERM).
  • trap 'commands' SIGNAL runs a handler; trap '' SIGNAL ignores; trap - SIGNAL restores the default; kill -s NAME $$ lets a script test its own handlers.
  • trap ... EXIT is the best place for cleanup because it runs on every way out except SIGKILL.
  • Handlers for INT and TERM should exit (with 130 or 143); handlers for USR1 or HUP usually return and let the script continue.
  • Background children are started with &, found in $!, and collected with wait, which returns their exit status; stop them in your cleanup with jobs -p.
  • Handlers run between commands, so wait for a background sleep if the loop needs to react quickly.

Next: Reading Input and Interactive Scripts