Open In App

Shell Scripting – Bash Trap Command

Last Updated : 12 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The trap command in Bash executes specific code in response to the signal given to the program. It traps the signal received by the program from the OS or the user and then executes the specific code provided by the programmer. It acts like a trigger in response to a signal. Just like try-catch statements help in exception handling, trap command helps in signal handling.

Prerequisites:  How to Send a signal to Processes, Bash Scripting, Shell Function Library

Syntax of the ‘Trap’ command

trap [-options] "piece of code" [signal name or value]
  • ‘-options’: Optional flags that modify the behavior of the trap command.
  • “code_to_execute”: The specific code or function you want to run when the signal is received.
  • ‘[signal_name or signal_value]’: The signal that triggers the trap, specified by name (e.g., SIGINT) or by value (e.g., 2).

Commonly Used Signals:

Signal Description
SIGINT (2) Interrupt signal, typically sent when pressing Ctrl+C.
SIGTERM (15) Termination signal, often used for stopping processes gracefully.
SIGKILL (9) Kill signal that forcefully terminates a process (cannot be trapped).
SIGTSTP (20) Stop signal, sent by pressing Ctrl+Z.
EXIT (0) A pseudo-signal received when the script exits.

Examples of Using the ‘trap’ Command

Let us take a look at some of the examples to better understand the command.

Example 1: Handling the SIGNIT Signal

Go to the Bash terminal and write the following command :

$ trap "echo Hello World" SIGINT

Now on pressing Ctrl+C, SIGINT(2) signal is sent to the terminal which is trapped by the trap command and the code echo hello world will be executed instead.

Ctrl+C sends SIGINT signal. We trap the signal and upon pressing Ctrl+C, the code is executed.

 

To revert back or remove the trap, write the command:

$ trap - SIGINT
Removing the trap of SIGINT signal

 

Example 2: Handling the SIGTSTP (STOP) Signal

Write the following command :

$ trap "echo This is a response to STOP signal" 20
Trapping SIGTSTP(20) signal

 

Signal value 20 corresponds to the stop signal SIGTSTP. Now on pressing Ctrl+Z, SIGTSTP(20) signal is sent to the terminal which is trapped by the trap command, and the code is executed instead.

To revert back write, use the command:

trap - 20

Example 3: Printing piece of the code (SIGINT)

$ trap "echo response to SIGINT" SIGINT
$ trap "echo response to SIGTSTP" SIGTSTP
$ trap -p
Listing the args/commands associated with each trapped signal

 

If only the ‘-p’ option is given, then it prints the piece of code we wrote associated with each signal.

$ trap -p SIGINT
Listing the command/piece of code associated with a particular SIGINT signal

 

If the ‘-p’ option is given with a signal value or signal name, then the commands/piece of code associated with that signal is displayed.

Example 4: Listing all the signals

To list all signals that can be trapped, use:

$ trap -l
Listing all signals that can be trapped

 

This command displays a list of all available signals, allowing you to see which signals can be managed with trap.

Creating Shell Script using the ‘trap’ Command

Let us understand the working of the trap command in detail by creating and executing some shell scripts.

Script 1: Hello World

The name of the script will be ‘bashTrap.sh‘.

$ touch bashTrap.sh

Make it an executable file.

$ chmod +x bashTrap.sh

Open the file and add the following script.

bashTrap.sh:

#!/bin/bash

trap "echo Hello World" SIGINT
while [[ true ]] ; do
    sleep 1
done

Run the script as a foreground process

$ ./bashTrap.sh
Ctrl+C doesn't terminate the process as the trap command traps the signal and executes the code

 

Explanation:

  • Whenever we press the keystroke ‘Ctrl+C‘, it sends an Interrupt signal SIGINT (signal value 2) to the program
  • Instead of the program getting terminated, the trap command traps the SIGINT signal and executes the code provided by us.
  • The infinite while loop is to make sure that the process keeps running and doesn’t exit too quickly before we send the signal to the process.
  • Finally, to get back to the shell prompt, press ‘Ctrl+Z‘ which will pause the process and then kill the process via the command ‘kill %jobspec’.

Script 2: Goodbye

Pseudo-signal EXIT(0) is received when the program exits from the shell. We can trap this signal and print a message when the shell process terminates.

bashTrap.sh:

#!/bin/bash

trap "echo Goodbye!" EXIT
sleep 1
When shell process exits, the exit signal is trapped and the command "echo goodbye" is executed

 

Explanation: When the script finishes or is terminated, the EXIT signal is received, and the trap prints “Goodbye!”.

Script 3: Function

We can also trigger different function calls in response to different signals with the help of a trap command. Run the following script as a background process.

bashTrap.sh:

#!/bin/bash

function trigger_sigint ()
{
  echo "This is a response to interrupt signal SIGINT(2)";
}
function trigger_sigcont ()
{
  echo -e "\nThis is a response to signal SIGCONT(18)";
}
function trigger_sigusr1 ()
{
  echo "This is a response to user signal SIGUSR1(10)"
}

trap trigger_sigint SIGINT
trap trigger_sigcont SIGCONT
trap trigger_sigusr1 SIGUSR1

while [[ true ]] ; do
  sleep 1;
done
Different response to different signals given by the user to the background process

Explanation: This script defines different functions to handle various signals. For example, pressing Ctrl+C triggers ‘trigger_sigint’, resuming a paused job triggers ‘trigger_sigcont’, and sending a user-defined signal triggers ‘trigger_sigusr1’.

Conclusion

The ‘trap’ command in Bash is a versatile tool that allows you to manage signals effectively, ensuring that your scripts are more reliable and maintainable. By using trap, you can gracefully handle interruptions, perform necessary cleanup tasks, and even execute custom code based on the signal received.

What is the trap command in Bash used for?

The trap command in Bash is used to execute specific code when a signal is received by a script. It helps handle interruptions or terminations by running predefined commands, such as cleanup operations or custom responses to signals like SIGINT or SIGTERM.

How does the trap command work?

The trap command intercepts signals sent to a program by the operating system or a user. When the specified signal is received, the trap executes the code or function provided by the programmer instead of allowing the default signal action to occur.

Can all signals be trapped using the trap command?

No, not all signals can be trapped. For example, the SIGKILL (9) signal, which forcefully terminates a process, cannot be trapped or ignored by the trap command.

How do you remove a trap for a signal in Bash?

You can remove a trap for a specific signal using the trap command followed by a dash and the signal name or number. For example, to remove a trap for SIGINT, use:

trap - SIGINT



Next Article
Article Tags :

Similar Reads

three90RightbarBannerImg