In this lesson, you will learn how to create "safety nets" in your scripts that execute cleanup tasks regardless of whether a script finishes successfully, crashes, or is forcibly interrupted by a user.
The Problem: Lingering State
When you run a script that creates temporary files, locks a resource, or opens a network socket, you want to ensure those items are removed or closed once the work is done. However, if a user presses Ctrl+C (sending a SIGINT signal) or the script encounters a fatal error, the execution stops immediately. These "leftovers" can clutter your system or, worse, prevent your script from running correctly the next time.
The Solution: The trap Command
Bash provides the trap command to intercept signals sent to your script. Instead of allowing the shell to exit instantly, trap catches the signal, runs a specific function or command, and then proceeds with the exit.
Consider this script structure:
#!/bin/bash
# Define a function to clean up
cleanup() {
echo "Cleaning up temporary files..."
rm -f /tmp/my_temp_file.txt
}
# Trap signals: EXIT (normal finish), SIGINT (Ctrl+C), SIGTERM (kill)
trap cleanup EXIT SIGINT SIGTERM
echo "Doing important work..."
touch /tmp/my_temp_file.txt
sleep 10
echo "Finished work."
In this example, the trap command tells Bash: "If you receive an EXIT, SIGINT, or SIGTERM, run the cleanup function first."
- If the script finishes normally, it hits
EXITand runscleanup. - If you press
Ctrl+Cwhile thesleepcommand is running, it catchesSIGINTand runscleanup. - If a system process kills the script, it catches
SIGTERMand runscleanup.
This ensures your environment remains clean, maintaining the integrity of your system regardless of how the script lifecycle is interrupted. By centralizing your cleanup logic, you transform unpredictable exits into controlled, graceful shutdowns.
Key Takeaway: Use the trap command to define a cleanup function that automatically triggers whenever your script terminates, preventing orphaned files and inconsistent states.