Skip to content
DevOps AI ToolKit
Newsletter
All prompts
AI for Bash & Python Automation Difficulty: Intermediate ClaudeChatGPT

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.

Run this prompt with AI

Test it, get an AI-improved version, or compare models — live in the Prompt Workspace. No copy-paste.

Related prompts

More Bash & Python Automation prompts & error guides

Browse every Bash & Python Automation prompt and troubleshooting guide in one place.

Free download · 368-page PDF

Reading prompts? Get all 500 in one free PDF

500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.

  • 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
  • Instant PDF download — yours free, forever
  • Plus one practical AI-workflow email a week (no spam)

Single opt-in · unsubscribe anytime · no spam.