BASH
Robust Script Cleanup with Trap
Ensure proper cleanup of temporary files or resources by using the `trap` command in Bash to execute specific actions on script exit, error, or interruption.
#!/bin/bash
TMP_FILE="/tmp/myscript_temp_$$"
cleanup() {
echo "Cleaning up temporary file $TMP_FILE..."
rm -f "$TMP_FILE"
}
# Trap EXIT, ERR, INT, TERM signals to run cleanup function
trap cleanup EXIT ERR INT TERM
# --- Main script logic ---
echo "Script started. Creating temporary file..."
touch "$TMP_FILE"
echo "Temporary file created at $TMP_FILE"
echo "Run some operations..."
sleep 5
# Simulate an error (uncomment to test)
# ls /nonexistent_directory
echo "Script finished successfully."
How it works: This script demonstrates how to use the `trap` command to register a `cleanup` function that will execute whenever the script exits (EXIT), encounters an unhandled error (ERR), is interrupted (INT, e.g., Ctrl+C), or receives a terminate signal (TERM). This ensures temporary files or other resources are properly removed, preventing leaks even if the script fails unexpectedly.