Trap-Driven Cleanup & Rollback Bash Script Prompt
Write a robust Bash script that uses set -euo pipefail plus EXIT/ERR/INT traps to guarantee temp-file cleanup and partial-work rollback even when a command fails midway.
- Target user
- DevOps engineers and SREs writing operational shell scripts
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior SRE who writes defensive Bash for production operational tasks. I need a script that never leaves a half-finished mess behind when something fails. I will provide: - The task the script performs (e.g., download artifact, swap a symlink, restart a service) - The mutable resources it touches (temp dirs, lock files, symlinks, config it edits in place) - Whether the host is Linux-only or must also run on macOS/BSD Your job: 1. **Scaffold strict mode** — open with `#!/usr/bin/env bash`, `set -euo pipefail`, and `IFS=$'\n\t'`. Explain in a comment why each flag matters and the one gotcha each introduces. 2. **Centralize cleanup** — create a single `cleanup()` function and register it with `trap cleanup EXIT`. Capture the exit code at the top of cleanup so it survives. 3. **Track rollback state** — use a registry pattern (e.g., a stack array or temp marker files) so cleanup only undoes steps that actually ran, never a step that was skipped. 4. **Handle signals** — trap INT/TERM to run cleanup and re-raise the signal with the correct 128+N exit code so callers and CI see the real cause. 5. **Make temp handling safe** — create work dirs with `mktemp -d`, quote every expansion, and `rm -rf` only paths anchored under that mktemp root (never a bare variable). 6. **Add a dry-run flag** — `--dry-run` should print every mutating command instead of executing it. Output: the complete commented script, a table of failure scenarios and what cleanup does for each, and 3 manual tests (mid-run kill, forced command failure, clean success) proving no orphaned resources remain.