---
name: write-safe-bash-scripts
description: Writes Bash scripts that stop at the first real failure, with strict mode, quoted variables, safe temp files and a cleanup trap. Use when the user wants a safe Bash script, set -euo pipefail, or a shell script that must not continue after an error.
license: MIT
metadata:
  category: deployment
  tags: "shell,ci,security"
  author: johnny-bravo
  version: "1.0"
  updated: "2026-11-07"
  status: published
  aliases: "bash strict mode, set -euo pipefail, defensive shell script"
  source_url: "https://github.com/wshobson/agents/tree/7e2fb559cf4b824b27f1fec49fe88f7511066d26/plugins/shell-scripting/skills/bash-defensive-patterns"
  source_license: MIT
  copyright: "Copyright (c) 2024 Seth Hobson"
  original_author: "Seth Hobson (wshobson/agents, bash-defensive-patterns)"
  modified: "Adapted by TheSkillVault: rewritten as a short checklist with one original script; dropped the pattern catalogue and reference file; added secret handling, a dry-run note, gotchas and done-when."
  imported_on: "2026-11-07"
---

# Write safe Bash scripts

A Bash script should stop when something fails, not keep going and wreck the next step. A few lines at the top prevent most of the silent damage.

## When to use
- You are writing a deploy, backup or cleanup script.
- A script kept going after a command failed, and later steps used bad data.
- Variables with spaces break a command because they were not quoted.

## When not to use
- You need a container image. That is a different task.
- The script must run under plain POSIX `sh` on a tiny device. Say so, and skip Bash-only syntax.

## Steps
1. Start with `#!/usr/bin/env bash` and `set -Eeuo pipefail`. `-e` stops on a failed command, `-u` stops on an unset variable, `pipefail` fails the pipe if any part fails, and `-E` lets functions inherit the error trap.
2. Quote every expansion: `"$file"`, never `$file`. Quote `"$@"` when you pass arguments on.
3. Require inputs up front. `: "${SRC:?Set SRC to the file to copy}"` exits with a clear line when the variable is missing.
4. Create temp files with `mktemp`. Register one `trap` on `EXIT` that deletes them. Do not use `/tmp/out` with a fixed name.
5. Check that a needed program exists with `command -v`, not `which`.
6. Prefer `[[ ]]` tests in Bash. Use `printf` instead of `echo` when the text must look the same on every machine.
7. Add a `--dry-run` flag for anything that deletes or overwrites. Print the command, and skip the real one.
8. Make the script safe to run twice. Creating a directory should use `mkdir -p`. Copying should not destroy a newer file by surprise.
9. Run it once with a missing variable, once with a failing command, and once on the happy path. All three should behave as you expect.

```bash
#!/usr/bin/env bash
set -Eeuo pipefail
src="${1:?Pass the file to archive}"
dest="${2:?Pass the destination directory}"
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT
[[ -f "$src" ]] || { printf 'No such file: %s\n' "$src" >&2; exit 1; }
mkdir -p -- "$dest"
cp -- "$src" "$tmp"
mv -- "$tmp" "$dest/$(basename -- "$src").bak"
trap - EXIT
```

## Gotchas
- `set -e` does not fire inside some `if` tests. That is useful. Do not wrap real work in `if` just to hide a failure.
- A pipe to `grep` can look successful when the earlier command failed, unless `pipefail` is on.
- Never put a password, token or API key in the script. Read it from the environment at run time, and do not `printf` it.
- `rm -rf "$dir"` is safe only when `dir` is checked and non-empty. An unset variable under `set -u` is a feature, not a nuisance. Do not turn `-u` off to "make it work".
- macOS ships an old Bash when you call `bash` from `/bin`. `#!/usr/bin/env bash` uses the one on `PATH`. Install a current Bash if you need newer syntax.

## Portability
These flags are Bash. If you use POSIX `sh`, drop `[[ ]]`, arrays and `mapfile`. Keep quoting, `set -eu`, `mktemp`, and tests for missing inputs. The same habits apply in zsh scripts, with that shell's options.

## Done when
- The script starts with strict mode, and a failed command stops it.
- Variables are quoted, temp files are removed on exit, and a dry run does not change files.
- No secret is stored in the file.

## Example prompt
"Write a Bash script that archives a directory to a dated folder. It must stop if the copy fails, quote every path, and support --dry-run."

---
Adapted from "bash-defensive-patterns" in wshobson/agents (MIT, Copyright (c) 2024 Seth Hobson). See LICENSE.txt.
