The goal of this tutorial is to provide a comprehensive understanding of how to use the 'trap' command for error handling in shell scripts. This will allow you to create more robust, reliable scripts that can handle unexpected events gracefully.
By the end of this tutorial, you will learn:
Prerequisites: Basic understanding of shell scripting is required.
The 'trap' command is a function built into bash and other shells that allows you to catch signals and execute a specified command when the signal is received. The syntax of the 'trap' command is as follows:
trap command signal
Here, 'command' is the command or function to be executed when the signal is caught, and 'signal' is the signal to be caught.
The signals that can be caught by the 'trap' command include:
Let's look at an example of using the 'trap' command:
#!/bin/bash
# Define cleanup procedure
cleanup() {
echo "Caught Interrupt ... cleaning up."
# Add your cleanup code here
}
# Setup trap
# catch interrupt (ctrl+c) signal
trap "cleanup" INT
# Your script
while true
do
echo "Sleeping ..."
sleep 1
done
In this script, we define a cleanup function. We then set a trap to catch the INT (interrupt) signal. If you run this script and press Ctrl+C, it will catch the interrupt signal and run the cleanup function.
In this tutorial, we learned about the 'trap' command and how to use it for error handling in shell scripts. We also learned how to catch signals and execute specific commands or functions on script exit.
To learn more about error handling in shell scripts, you can refer to the man pages for the bash shell, or consult online resources.
Write a shell script that sets a trap for the EXIT signal and prints a message when the script exits.
Write a shell script that sets a trap for the ERR signal and prints a message when a command fails in the script.
Modify the script from exercise 2 to execute a cleanup function when a command fails in the script.
Here's a solution for exercise 1:
```bash
trap "echo 'Script exiting...'" EXIT
echo "Hello, World!"
```
This script will print "Script exiting..." when it exits.
Here's a solution for exercise 2:
```bash
trap "echo 'A command failed.'" ERR
echo "Hello, World!"
false # This command will fail
```
This script will print "A command failed." when the 'false' command fails.
Here's a solution for exercise 3:
```bash
cleanup() {
echo "A command failed. Cleaning up..."
# Add your cleanup code here
}
trap "cleanup" ERR
echo "Hello, World!"
false # This command will fail
```
This script will run the cleanup function when the 'false' command fails.