Traps for Signal Handling

Sets up trap handlers for signals like EXIT, INT, TERM, and ERR to ensure cleanup, graceful shutdown, and error recovery in Bash scripts.

BashResilience

Code

bashsnippet
46 lines
#!/usr/bin/env bash
set -euo pipefail

temp_files=()
cleanup_performed=false

cleanup() {
    if [[ "$cleanup_performed" == false ]]; then
        cleanup_performed=true
        echo "Performing cleanup..."
        for f in "${temp_files[@]}"; do
            [[ -f "$f" ]] && rm -f "$f"
        done
        echo "Cleanup complete"
    fi
}

on_error() {
    local line=$1
    echo "Error occurred at line $line" >&2
    cleanup
    exit 1
}

on_interrupt() {
    echo ""
    echo "Interrupted by user, cleaning up..." >&2
    cleanup
    exit 130
}

trap cleanup EXIT
trap 'on_error $LINENO' ERR
trap on_interrupt INT TERM

# Create temp files
for i in 1 2 3; do
    tmp=$(mktemp "/tmp/demo-$$-XXXXXX")
    temp_files+=("$tmp")
    echo "data $i" > "$tmp"
done

echo "Temp files created: ${temp_files[*]}"
echo "Processing..."
sleep 2
echo "Work complete"

trap registers handlers for signals and events: EXIT runs on any exit, ERR on command failure, INT on Ctrl+C, TERM on termination. This ensures cleanup (temp file removal) runs regardless of how the script exits. $LINENO provides the error line number. The cleanup_performed flag prevents double-cleanup. Exit code 130 conventionally indicates Ctrl+C termination.

Interactive Tools for This Topic