In this tutorial, we will delve into the world of Signal Processing in shell scripts. We aim to introduce you to the concept of managing software interrupts or signals in a Unix/Linux environment.
By the end of this tutorial, you will have learned:
Prerequisites for this tutorial include a basic understanding of shell scripting and Unix/Linux commands.
In Unix/Linux systems, signals are software interrupts that provide a way to handle asynchronous events. Different signals have different uses. For example, the SIGINT signal interrupts the process, while the SIGTERM signal requests the process to terminate.
In shell scripts, we can use the trap
command to capture and handle signals. The syntax is:
trap 'commands' signal-list
Where 'commands' are the commands to be executed when any signal from the 'signal-list' is received.
#!/bin/sh
# Define a function to handle the SIGINT signal (CTRL+C)
handle_interrupt() {
echo "Interrupt signal received. Cleaning up..."
exit 1 # Exit the script
}
# Use the trap command to capture the SIGINT signal
trap 'handle_interrupt' SIGINT
# The main script
while true; do
echo "Press CTRL+C to exit."
sleep 1 # Wait for 1 second
done
In the above script, if you press CTRL+C while the script is running, the handle_interrupt
function will be called, and the script will exit.
#!/bin/sh
temp_file="/tmp/my_script.$$"
# Create a temporary file
touch $temp_file
# Define a function to clean up the temporary file
clean_up() {
echo "Cleaning up temporary file..."
rm $temp_file
exit 1
}
# Use the trap command to capture the SIGINT and SIGTERM signals
trap 'clean_up' SIGINT SIGTERM
# The main script
while true; do
echo "Press CTRL+C or send a SIGTERM signal to exit."
sleep 1
done
In this example, if the script receives a SIGINT or SIGTERM signal, it will call the clean_up
function, which removes the temporary file and exits the script.
In this tutorial, we have covered the basics of signal processing in shell scripts, including how to capture and handle signals and use them to control script execution. We have also learned the importance of cleaning up temporary files when the script is interrupted.
For further learning, you could explore more about other types of signals and how they can be used in shell scripts.
Exercise 1: Write a shell script that waits for a SIGUSR1 signal, and then prints a message.
Exercise 2: Modify the above script to catch a SIGUSR2 signal as well, and print a different message.
Exercise 3: Write a script that creates a temporary file, writes the PID of the script to the file, catches the SIGINT and SIGTERM signals, and cleans up the temporary file when these signals are received.
Remember to practice regularly and experiment with different signals and trap commands to get a better understanding of signal processing in shell scripts.