Interview Prep/Shell Scripting/Troubleshooting: quoting, expansion and tool-input bugs

`ssh web1 "rm -rf /srv/app/releases/$old"` deleted the wrong directory when `$old` contained a space. How did that happen?

AdvancedTroubleshootingTroubleshooting: quoting, expansion and tool-input bugs
Answer

Likely causes → The command is expanded locally, sent as a string, and then parsed again by the remote shell. old="2026 old" becomes rm -rf /srv/app/releases/2026 old remotely: it deletes releases/2026 and ./old in the remote home directory. A crafted value could run arbitrary commands.

Diagnose → Replace ssh web1 with echo to see the exact string the remote shell will parse.

Fix → Validate the value, and quote it for the remote shell with printf %q:

[[ $old =~ ^[0-9]{8}T[0-9]{6}Z$ ]] || die "invalid release name: $old"
ssh web1 "rm -rf -- /srv/app/releases/$(printf '%q' "$old")"

Or pass it as an argument to a remote script: ssh web1 bash -s -- "$old" < cleanup.sh (still validate).

Prevent → Treat every remote command string as code; validate inputs and quote with %q.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: quoting, expansion and tool-input bugs