Bash trap Command Explained

December 16, 2021

Introduction

A shell script can run into problems during its execution, resulting in an error signal that interrupts the script unexpectedly.

Errors occur due to a faulty script design, user actions, or system failures. A script that fails may leave behind temporary files that cause trouble when a user restarts the script.

This tutorial will show you how to use the trap command to ensure your scripts always exit predictably.

Bash trap command explained.

Prerequisites

  • Access to the terminal/command line.
  • A text editor (Nano, Vi/Vim, etc.).

Bash trap Syntax

The syntax for the trap command is:

trap [options] "[arguments]" [signals]

The command has the following components:

  • Options provide added functionality to the command.
  • Arguments are the commands trap executes upon detecting a signal. Unless the command is only one word, it should be enclosed with quotation marks (" "). If the argument contains more than one command, separate them with a semicolon (;).
  • Signals are asynchronous notifications sent by the system, usually indicating a user-generated or system-related interruption. Signals can be called by their name or number.

Bash trap Options

The trap command accepts the following options:

  • -p - Displays signal commands.
  • -l - Prints a list of all the signals and their numbers.

Below is the complete list of the 64 signals and their numbers:

#Signal#Signal#Signal
1SIGHUP23SIGURG45SIGRTMIN+11
2SIGINT24SIGXCPU46SIGRTMIN+12
3SIGQUIT25SIGXFSZ47SIGRTMIN+13
4SIGILL26SIGVTALRM48SIGRTMIN+14
5SIGTRAP27SIGPROF49SIGRTMIN+15
6SIGABRT28SIGWINCH50SIGRTMAX-14
7SIGBUS29SIGIO51SIGRTMAX-13
8SIGFPE30SIGPWR52SIGRTMAX-12
9SIGKILL31SIGSYS53SIGRTMAX-11
10SIGUSR132SIGWAITING54SIGRTMAX-10
11SIGSEGV33SIGLWP55SIGRTMAX-9
12SIGUSR234SIGRTMIN56SIGRTMAX-8
13SIGPIPE35SIGRTMIN+157SIGRTMAX-7
14SIGALRM36SIGRTMIN+258SIGRTMAX-6
15SIGTERM37SIGRTMIN+359SIGRTMAX-5
16SIGSTKFLT38SIGRTMIN+460SIGRTMAX-4
17SIGCHLD39SIGRTMIN+561SIGRTMAX-3
18SIGCONT40SIGRTMIN+662SIGRTMAX-2
19SIGSTOP41SIGRTMIN+763SIGRTMAX-1
20SIGTSTP42SIGRTMIN+864SIGRTMAX
21SIGTTIN43SIGRTMIN+9
22SIGTTOU44SIGRTMIN+10

Note: Signals 32 and 33 are not supported in Linux, and the trap -l command does not display them in the output.

The signals most commonly used with the trap command are:

  • SIGHUP (1) - Clean tidy-up
  • SIGINT (2) - Interrupt
  • SIGQUIT (3) - Quit
  • SIGABRT (6) - Cancel
  • SIGALRM (14) - Alarm clock
  • SIGTERM (15) - Terminate

Note: The SIG prefix in signal names is optional. For example, SIGTERM signal can also be written as TERM.

How to Use trap in Bash

A typical scenario for using the trap command is catching the SIGINT signal. This signal is sent by the system when the user interrupts the execution of the script by pressing Ctrl+C.

The following example script prints the word "Test" every second until the user interrupts it with Ctrl+C. The script then prints a message and quits.

trap "echo The script is terminated; exit" SIGINT

while true
do
    echo Test
    sleep 1
done

The while loop in the example above executes infinitely. The first line of the script contains the trap command and the instructions to wait for the SIGINT signal, then print the message and exit the script.

Executing the trap-test.sh script and terminating it with Ctrl+C.

The trap command is frequently used to clean up temporary files if the script exits due to interruption. The following example defines the cleanup function, which prints a message, removes all the files added to the $TRASH variable, and exits the script.

$TRASH=$(mktemp -t tmp.XXXXXXXXXX)

trap cleanup 1 2 3 6

cleanup()
{
  echo "Removing temporary files:"
  rm -rf "$TRASH"
  exit
}

...

The trap in the example above executes the cleanup function when it detects one of the four signals: SIGHUP, SIGINT, SIGQUIT, or SIGABRT. The signals are referred to by their number.

You can also use trap to ensure the user cannot interrupt the script execution. This feature is important when executing sensitive commands whose interruption may permanently damage the system. The syntax for disabling a signal is:

trap "" [signal]

Double quotation marks mean that no command will be executed. For example, to trap the SIGINT and SIGABRT signals, type:

trap "" SIGINT SIGABRT
[a command that must not be interrupted]

If you wish to re-enable the signals at any time during the script, reset the rules by using the dash symbol:

trap - SIGINT SIGABRT
[a command that can be interrupted]

Note: The SIGKILL signal cannot be trapped. It always immediately interrupts the script.

Conclusion

After reading this tutorial, you know how to use the trap command to ensure your bash script always exits properly. If you are interested in more Bash-related topics, read How to Run a Bash Script.

Was this article helpful?
YesNo
Marko Aleksic
Marko Aleksić is a Technical Writer at phoenixNAP. His innate curiosity regarding all things IT, combined with over a decade long background in writing, teaching and working in IT-related fields, led him to technical writing, where he has an opportunity to employ his skills and make technology less daunting to everyone.
Next you should read
Bash Script for Loop Explained with Examples
December 15, 2021

Whether you're going through an array of numbers or renaming files, for loops in Bash scripts provide a convenient way to list items automatically. This tutorial shows how to use Bash for loops in scripts.
Read more
Bash case Statement Syntax and Examples
December 15, 2021

The case statement is an excellent choice for creating menus where users select an option which triggers a corresponding action. In this tutorial, you will learn the bash case statement basics and how to use it in shell scripts.
Read more
Bash Function & How to Use It
November 3, 2021

The functions are available for most programming languages, known under different names such as procedures, methods, or subroutines. This article provides a complete overview of bash functions, how they work, and how to use them.
Read more
How to Comment in Bash
November 30, 2021

Commenting out code for later use is a common practice and is an essential part of programming and bash scripting. This tutorial demonstrates how to use comments and the best commenting practices in bash scripts.
Read more
  • © 2021 Copyright phoenixNAP | Global IT Services. All Rights Reserved.