Shell Scripting – Bash Trap Command
Last Updated :
12 Sep, 2024
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.
To revert back or remove the trap, write the command:
$ trap - SIGINT
Example 2: Handling the SIGTSTP (STOP) Signal
Write the following command :
$ trap "echo This is a response to STOP signal" 20
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
If only the ‘-p’ option is given, then it prints the piece of code we wrote associated with each signal.
$ trap -p SIGINT
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
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
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
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
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
Similar Reads
Shell Scripting - True Command
A shell provides an interface with the help of which users can interact with the system easily. To directly interact with a shell, we use an operating system. On a Unix-based operating system, every time we write a command using a terminal, we interact with the system. To interpret or analyze Unix c
3 min read
Shell Scripting - Shopt Command
Unlike many shell commands, shopt is a bash-only shell command. It is a built-in BASH shell command that controls certain options for the shell session. One can consider this as a boolean ON/OFF switch for certain shell options. The âshoptâ command provides control over many settings that are used t
7 min read
Shell Scripting - JOB SPEC & Command
Prerequisites: Bash Scripting, Shell Function Library Processes started from the terminal (and still not terminated) get a unique serial number or ID that is known as job spec or job ID. With the help of the job spec of a particular process, we can send signals to it or make that particular process
3 min read
Shell Scripting - Set Command
The `set` command in shell scripting is a powerful tool that used for controlling the behavior of the shell and the environment in which scripts run. It allows the users to modify the shell options and positional parameters which facilitates providing greater control over script execution and debugg
7 min read
Shell Scripting - Disown Command
Shell is a command language interpreter. It is used in most of the UNIX/LINUX-based distros. Shell support scripting means we can automate the Shell commands by writing some scripts with different logic, looping, and decision making. This benefits us to automate some time-consuming and tedious jobs.
5 min read
Shell Scripting - Logout Command
The Linux logout command is a quick utility that allows you to log out of your present terminal session. It's similar to the action of clicking "Log Out" on the desktop of a computer, but for the terminal. It's particularly handy if you're using a login shellâa special terminal session associated wi
4 min read
Shell Scripting - Define #!/bin/bash
A shell provides an interface to connect with the system. When we use an operating system, we indirectly interact with the shell. While using a terminal every time on any Linux distribution system, we interact with the shell. The main function of the shell is to interpret or analyze Unix commands. A
3 min read
Shell Scripting - Command Substitution
A shell is an interface that helps users to connect with the system. Using a shell is equivalent to indirectly communicating with the operating system. In Linux distributed systems, each time we use the terminal, we connect with a shell. The job of a shell is to analyze Unix commands or instructions
4 min read
Bash Scripting - Case Statement
A case statement in bash scripts is used when a decision has to be made against multiple choices. In other words, it is useful when an expression has the possibility to have multiple values. This methodology can be seen as a replacement for multiple if-statements in a script. Case statements have an
8 min read
Bash Scripting - String
Bash String is a data type similar to integer or boolean. It is generally used to represent text. It is a string of characters that may also contain numbers enclosed within double or single quotes. Example: "geeksforgeeks", "Geeks for Geeks" or "23690" are strings Creating a String A basic declarati
2 min read