Introduction
In this lab, we will explore the trap command in Bash scripting. The trap command is a powerful tool that allows you to catch and handle signals, interruptions, and user inputs in your scripts. By using trap, you can define specific actions to be taken when particular signals are received, enabling you to manage unpredictable behavior and gracefully handle various scenarios. This lab is designed for beginners and will guide you through the process of using the trap command effectively.
Create a Bash Script
Let's start by creating a new Bash script file where we'll implement the trap command.
Open a terminal in the WebIDE. You should see a prompt ending with a
$symbol.Navigate to the project directory:
cd ~/projectThis command changes your current working directory to
/home/labex/project.Create a new file named
trap_example.sh:touch trap_example.shThe
touchcommand creates an empty file if it doesn't exist, or updates the modification time if it does.Open the
trap_example.shfile in the WebIDE editor. You can do this by clicking on the file name in the file explorer on the left side of the WebIDE.
Implement a Basic Trap Command
Now, let's implement a basic trap command in our script to catch specific signals and exit gracefully.
Add the following content to the
trap_example.shfile:#!/bin/bash cleanup_and_exit() { echo -e "\nSignal received! Cleaning up and exiting..." exit 0 } trap cleanup_and_exit SIGINT SIGTERM echo "This script will run until you press Ctrl+C." echo "Press Ctrl+C to see the trap in action and exit gracefully." count=1 while true; do echo "Script is running... (iteration $count)" sleep 1 ((count++)) doneLet's break down this script:
- The first line
#!/bin/bashis called a shebang. It tells the system that this script should be executed by the Bash shell. - We define a
cleanup_and_exitfunction that prints a message and exits the script. - The
trapcommand is set up to callcleanup_and_exitwhen it catches either SIGINT (interrupt) or SIGTERM (termination) signals. SIGINT is typically sent when you press Ctrl+C, while SIGTERM is often used when a process is asked to terminate gracefully. - The
echocommands print instructions for the user. - The
whileloop runs indefinitely, printing a message and incrementing a counter every second.
- The first line
Save the file after adding the content.
Make the Script Executable and Run It
Before we can run our script, we need to make it executable. This tells the system that this file is allowed to be run as a program.
In the terminal, make the script executable:
chmod +x ~/project/trap_example.shThe
chmodcommand changes the permissions of a file. The+xoption adds execute permission.Run the script:
~/project/trap_example.shThis command tells Bash to execute our script.
The script will start running. You'll see the instructions printed on the screen. Let it run for a few seconds.
Now, press Ctrl+C to interrupt it. You should see the message "Signal received!" before the script exits. This is our trap in action!
Modify the Trap to Use a Function
Instead of using a simple function, let's modify our script to use a more complex function with the trap command. This allows us to perform more detailed actions when a signal is received.
Open the
trap_example.shfile in the WebIDE editor.Replace the content of the file with the following:
#!/bin/bash cleanup_and_exit() { echo -e "\nSignal received! Cleaning up..." echo "Performing cleanup tasks..." ## Add any necessary cleanup code here echo "Cleanup completed." echo "Exiting script gracefully." exit 0 } trap cleanup_and_exit SIGINT SIGTERM echo "This script will run until you press Ctrl+C." echo "Press Ctrl+C to see the trap function in action and exit gracefully." count=1 while true; do echo "Script is running... (iteration $count)" sleep 1 ((count++)) doneLet's examine the changes:
- We've expanded the
cleanup_and_exitfunction to include more detailed messages and a placeholder for cleanup tasks. - The function now simulates a more realistic cleanup process, which could include tasks like closing file handles, removing temporary files, or releasing other resources.
- We've updated the main loop to show an iteration count, making it clearer that the script is actively running.
- We've expanded the
Save the file after making these changes.
Run the script again and test it by pressing Ctrl+C:
~/project/trap_example.shYou should see the new messages from the
cleanup_and_exitfunction when you interrupt the script, demonstrating a graceful exit.
Summary
In this lab, you learned how to use the trap command in Bash scripting. You created a script that catches specific signals and defines actions to be taken when those signals are received. You explored different ways of using the trap command, including using inline commands and functions.
The trap command is a powerful tool for handling interruptions and performing cleanup actions in your Bash scripts. It allows you to create more robust and user-friendly command-line applications by gracefully handling unexpected terminations and user interrupts.
Remember, the ability to handle signals can be crucial in many scripting scenarios, such as ensuring proper cleanup of temporary files, closing network connections, or saving state before a script exits unexpectedly.



