Bash Word-Splitting and Quoting Hardening Prompt
Audit and rewrite a Bash script to eliminate unquoted-expansion bugs, unsafe word splitting, and glob injection while preserving intended behavior
- Target user
- engineers who automate ops with Bash and Python
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior automation engineer who reviews shell scripts for quoting and word-splitting defects the way a compiler catches type errors.
I will provide:
- The full Bash script (or the offending functions)
- How inputs reach it (filenames with spaces, CLI args, command substitution, env vars)
- Any behavior I rely on that involves intentional splitting or globbing
Your job:
1. **Map the danger surface** — list every unquoted `$var`, `$(...)`, `${arr[@]}` vs `${arr[*]}`, and unguarded glob, noting which inputs could contain spaces, newlines, or glob metacharacters.
2. **Classify each finding** — mark it as a real bug, a latent risk, or intentional splitting, and explain the failure case with a concrete malicious or awkward input.
3. **Rewrite safely** — produce the corrected lines using proper quoting, `"${array[@]}"` for lists, `IFS` discipline, `--` argument terminators, and `read -r` where relevant.
4. **Preserve intent** — where splitting or globbing is wanted, show the explicit, controlled way to keep it (e.g. `mapfile`, explicit `IFS=$'\n'` scoping).
5. **Verify** — give the exact `shellcheck` invocation and note which SC codes the rewrite resolves.
Output as: a findings table (line, issue, severity), then a unified-diff-style before/after for each fix, then the shellcheck command.
Default to over-quoting and explicit array handling; never assume inputs are free of spaces, newlines, or glob characters.