Handling Interruption with Cleanup Functions
To handle interruptions in your shell scripts, you can use cleanup functions. These functions are designed to perform cleanup tasks when a script is interrupted, ensuring that the system is left in a consistent and stable state.
Defining a Cleanup Function
To define a cleanup function, you can use the following syntax:
cleanup() {
## Cleanup tasks go here
echo "Cleaning up resources..."
rm -f /tmp/myfile.txt
## Add more cleanup tasks as needed
}
In this example, the cleanup()
function removes a temporary file located at /tmp/myfile.txt
. You can add more cleanup tasks as needed, such as closing network connections, releasing database connections, or undoing partial changes.
Registering the Cleanup Function
To ensure that the cleanup function is executed when the script is interrupted, you need to register it using the trap
command. The trap
command allows you to specify a function to be executed when a specific signal is received by the script.
Here's an example of how to register the cleanup function:
## Register the cleanup function to be executed on script interruption
trap cleanup SIGINT SIGTERM
In this example, the trap
command registers the cleanup()
function to be executed when the script receives a SIGINT
(Ctrl+C) or SIGTERM
(termination) signal.
Handling Interruption in Your Script
Now, whenever your script is interrupted, the registered cleanup function will be executed. This ensures that any resources used by the script are properly cleaned up, leaving the system in a consistent state.
Here's an example of a shell script that demonstrates the use of a cleanup function:
#!/bin/bash
## Define the cleanup function
cleanup() {
echo "Cleaning up resources..."
rm -f /tmp/myfile.txt
}
## Register the cleanup function to be executed on script interruption
trap cleanup SIGINT SIGTERM
## Create a temporary file
touch /tmp/myfile.txt
## Simulate a long-running task
echo "Running script... (Press Ctrl+C to interrupt)"
while true; do
sleep 1
done
In this example, the script creates a temporary file at /tmp/myfile.txt
and then enters an infinite loop to simulate a long-running task. If the script is interrupted by pressing Ctrl+C
or by sending a SIGTERM
signal, the registered cleanup()
function will be executed, and the temporary file will be removed.
By using cleanup functions, you can ensure that your shell scripts are more reliable and resilient, even in the face of unexpected interruptions.