You can use the trap command in a Bash script to handle signals by specifying the signal you want to catch and the command or function to execute when that signal is received. Here’s a basic example:
#!/bin/bash
# Define a cleanup function
cleanup() {
echo "Cleaning up before exit..."
# Add any cleanup commands here
exit 0
}
# Set up the trap to catch SIGINT (Ctrl+C) and SIGTERM
trap cleanup SIGINT SIGTERM
# Main script logic
echo "Running script. Press Ctrl+C to interrupt."
while true; do
sleep 1
done
Explanation:
- Cleanup Function: The
cleanupfunction is defined to perform any necessary cleanup actions before the script exits. - Trap Command: The
trapcommand is set to call thecleanupfunction when either the SIGINT or SIGTERM signal is received. - Main Logic: The script enters an infinite loop, simulating ongoing work. If you press Ctrl+C, the
cleanupfunction will be executed, allowing for graceful termination.
You can customize the cleanup function to include any commands needed for your specific use case.
