Use `trap` to clean up a temp directory on exit, even on Ctrl+C or error.
IntermediateHands-onBash scripting tasks
Answer
#!/usr/bin/env bash
set -euo pipefail
TMP="$(mktemp -d)"
cleanup() { rm -rf "$TMP"; echo "cleaned $TMP"; }
trap cleanup EXIT
trap 'echo "interrupted"; exit 130' INT TERM
curl -sfo "$TMP/release.tgz" https://example.com/release.tgz
tar -xzf "$TMP/release.tgz" -C "$TMP"
Key trick → Trapping EXIT covers normal exit, set -e failures and the explicit exit 130 from the INT handler, so cleanup runs in all three cases.
More on Bash scripting tasks
Write the safe header you start every Bash script with, and explain each part.BeginnerWrite a script that alerts when any filesystem is above 80% usage.BeginnerParse an Nginx access log and print the top 10 client IPs by request count.BeginnerWrite a backup script that tars a directory with a timestamp and keeps only the last 7 backups.IntermediateWrite a health-check loop that polls a URL until it returns 200, with a timeout.IntermediateParse command-line flags `-e <env>`, `-v` (verbose) and `-h` in a Bash script.Intermediate