Bash

Trap Signals for Cleanup

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Use `trap` to delete temp files / kill background workers when the script exits — even on Ctrl-C or an unhandled error. Single most-undervalued bash feature.
Bash
Raw
#!/usr/bin/env bash
set -euo pipefail

WORK="$(mktemp -d)"
echo "Working in $WORK"

cleanup() {
    local rc=$?
    rm -rf "$WORK"
    echo "Cleaned up (exit code $rc)"
    exit $rc
}

# EXIT covers normal exit AND errexit
# INT covers Ctrl-C; TERM covers `kill`
trap cleanup EXIT INT TERM

# Do work that might fail — cleanup runs no matter what
cd "$WORK"
curl -s https://example.com -o data.html
process data.html
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.