Bash Trap Command

ShellShellBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In Bash scripting, the trap command allows you to catch and handle signals, interruptions, and user inputs in your script. By using trap, you can define specific actions to be taken when a particular signal is received, allowing you to prevent unpredictable behavior and gracefully handle various scenarios.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("`Linux`")) -.-> linux/BasicSystemCommandsGroup(["`Basic System Commands`"]) linux(("`Linux`")) -.-> linux/FileandDirectoryManagementGroup(["`File and Directory Management`"]) linux(("`Linux`")) -.-> linux/BasicFileOperationsGroup(["`Basic File Operations`"]) shell(("`Shell`")) -.-> shell/BasicSyntaxandStructureGroup(["`Basic Syntax and Structure`"]) shell(("`Shell`")) -.-> shell/ControlFlowGroup(["`Control Flow`"]) shell(("`Shell`")) -.-> shell/FunctionsandScopeGroup(["`Functions and Scope`"]) shell(("`Shell`")) -.-> shell/SystemInteractionandConfigurationGroup(["`System Interaction and Configuration`"]) linux/BasicSystemCommandsGroup -.-> linux/sleep("`Execution Delaying`") linux/BasicSystemCommandsGroup -.-> linux/exit("`Shell Exiting`") linux/BasicSystemCommandsGroup -.-> linux/echo("`Text Display`") linux/FileandDirectoryManagementGroup -.-> linux/cd("`Directory Changing`") linux/BasicFileOperationsGroup -.-> linux/rm("`File Removing`") linux/BasicFileOperationsGroup -.-> linux/touch("`File Creating/Updating`") linux/BasicFileOperationsGroup -.-> linux/chmod("`Permission Modifying`") shell/BasicSyntaxandStructureGroup -.-> shell/shebang("`Shebang`") shell/BasicSyntaxandStructureGroup -.-> shell/comments("`Comments`") shell/BasicSyntaxandStructureGroup -.-> shell/quoting("`Quoting Mechanisms`") shell/ControlFlowGroup -.-> shell/while_loops("`While Loops`") shell/ControlFlowGroup -.-> shell/until_loops("`Until Loops`") shell/ControlFlowGroup -.-> shell/exit_status("`Exit and Return Status`") shell/FunctionsandScopeGroup -.-> shell/func_def("`Function Definition`") shell/SystemInteractionandConfigurationGroup -.-> shell/trap_statements("`Trap Statements`") subgraph Lab Skills linux/sleep -.-> lab-153904{{"`Bash Trap Command`"}} linux/exit -.-> lab-153904{{"`Bash Trap Command`"}} linux/echo -.-> lab-153904{{"`Bash Trap Command`"}} linux/cd -.-> lab-153904{{"`Bash Trap Command`"}} linux/rm -.-> lab-153904{{"`Bash Trap Command`"}} linux/touch -.-> lab-153904{{"`Bash Trap Command`"}} linux/chmod -.-> lab-153904{{"`Bash Trap Command`"}} shell/shebang -.-> lab-153904{{"`Bash Trap Command`"}} shell/comments -.-> lab-153904{{"`Bash Trap Command`"}} shell/quoting -.-> lab-153904{{"`Bash Trap Command`"}} shell/while_loops -.-> lab-153904{{"`Bash Trap Command`"}} shell/until_loops -.-> lab-153904{{"`Bash Trap Command`"}} shell/exit_status -.-> lab-153904{{"`Bash Trap Command`"}} shell/func_def -.-> lab-153904{{"`Bash Trap Command`"}} shell/trap_statements -.-> lab-153904{{"`Bash Trap Command`"}} end

Create a Bash Script

Create a new file ~/project/trap_example.sh. This will be our Bash script where we will implement the trap command.

cd ~/project
touch trap_example.sh

Declare the Trap Command

Inside the trap_example.sh file, declare the trap command to catch specific signals and define the actions to be taken when those signals are received.

#!/bin/bash
## trap_example.sh

trap "echo Booh!" SIGINT SIGTERM
echo "The script will run until you hit Ctrl+Z."
echo "Hit Ctrl+C to display a message!"

while true; do
  sleep 60
done

In this example, we are catching the SIGINT (interrupt) and SIGTERM (termination) signals. When either of these signals is received, the script will execute the specified action, which, in this case, is to display the message "Booh!".

Run the Script

Make the script executable using the chmod +x command:

chmod +x trap_example.sh

Run the script:

./trap_example.sh

Test the Trap Command

While the script is running, try the following actions to test the trap command:

  1. Press Ctrl+C - The script should display the message "Booh!".
  2. Press Ctrl+Z - The script should continue running in the background.
  3. Run kill -l in the terminal - This command will display a list of all available signals. Take note of their numbers.

Refactor the Trap Action

Instead of using an inline message in the trap command, let's refactor it to use a function. Add a function definition to the script:

function booh {
  echo "Booh!"
}

Now, modify the trap command to use the booh function as the action:

trap booh SIGINT SIGTERM

Use Signal Numbers in the Trap Command

Instead of using signal names in the trap command, you can also use their corresponding numbers. We can use the earlier command kill -l to determine the numbers. Modify the trap command to use signal numbers:

trap booh 2 15

In this example, 2 corresponds to SIGINT and 15 corresponds to SIGTERM.

Perform Cleanup with Trap

One common usage of the trap command is to perform cleanup activities, such as deleting temporary files. Add a command to delete a folder and exit the script when a specific signal is received:

trap "rm -f folder; exit" 2

In this example, when the SIGINT signal is received (Ctrl+C), the script will delete the folder named folder and then exit gracefully.

Summary

In this lab, you learned how to use the trap command in Bash scripting. By catching specific signals and defining the actions to be taken, you can control the behavior of your script and handle user inputs and interruptions effectively. The trap command allows you to gracefully handle unexpected scenarios and perform cleanup activities when necessary.

Other Shell Tutorials you may like