BASH
Implement Robust Script Cleanup with Trap
Ensure Bash scripts clean up temporary files or stop background processes automatically upon exit or interruption using the 'trap' command for reliability.
#!/bin/bash
# --- Configuration and temporary resource setup ---
# Create a unique temporary directory for this script instance
TMP_DIR=$(mktemp -d -t myapp-XXXXXXXX)
TMP_FILE="$TMP_DIR/temp_data.txt"
BACKGROUND_PID=""
# --- Cleanup function ---
# This function will be called on script exit or interruption
cleanup() {
echo "
--- Running cleanup function ---"
# Remove temporary directory and its contents
if [ -d "$TMP_DIR" ]; then
echo "Removing temporary directory: $TMP_DIR"
rm -rf "$TMP_DIR"
fi
# Kill any background processes started by this script
if [ -n "$BACKGROUND_PID" ]; then
echo "Killing background process with PID: $BACKGROUND_PID"
kill "$BACKGROUND_PID" 2>/dev/null # Suppress error if process already dead
fi
echo "Cleanup complete."
}
# --- Set up traps ---
# The cleanup function will be executed when the script receives:
# EXIT: Upon normal or abnormal termination
# INT: Interrupt signal (e.g., Ctrl+C)
# TERM: Terminate signal (e.g., `kill <pid>`)
trap cleanup EXIT INT TERM
echo "Script started. Temporary directory created: $TMP_DIR"
# --- Simulate script work ---
echo "Working with temporary file: $TMP_FILE"
echo "Hello World" > "$TMP_FILE"
cat "$TMP_FILE"
# Simulate a background process that needs to be cleaned up
( while true; do echo "Background process running..."; sleep 2; done ) & # Run in background
BACKGROUND_PID=$!
echo "Background process started with PID: $BACKGROUND_PID"
# Simulate a long-running task. Try pressing Ctrl+C during this sleep.
echo "
Sleeping for 10 seconds (try Ctrl+C to test cleanup)...
(You should see 'Cleaning up...' messages after interruption)"
sleep 10
echo "
Script finished successfully. (Cleanup will still run on EXIT)"
How it works: This snippet demonstrates the critical `trap` command for robust script cleanup. It defines a `cleanup` function that handles tasks like removing temporary directories created with `mktemp -d` and killing any background processes started by the script. The `trap cleanup EXIT INT TERM` command ensures this function is automatically invoked when the script exits (normally or abnormally), receives an interrupt signal (like Ctrl+C), or a termination signal. This prevents resource leaks and ensures your automation scripts leave a clean state, even if they fail unexpectedly or are manually stopped.