Safe Bash: Quoting and set -euo pipefail
Bash is the language of incident response one-liners, cron jobs and installer scripts, and it has a dangerous default: it splits and expands every unquoted variable. A file called my report.txt becomes two arguments, a file called * becomes every file in the directory, a file called -rf becomes an option, and an empty variable can turn rm -rf "$DIR/" into rm -rf /. In a security context these are not curiosities: an attacker who can create a file name (an upload, a mail attachment, a home directory) can steer a privileged script. The shell basics are in Linux & Bash; this lesson is the defensive subset.
The session runs in your sandbox with no network; the hostile names are files it creates in its own directory.
Definitions
- Word splitting: an unquoted
$varis split at spaces, tabs and newlines (IFS) into several words. - Pathname expansion (globbing): an unquoted word containing
*,?or[is replaced by matching file names. - Quoting:
"$var"is always exactly one word, with no splitting and no globbing."$@"passes every argument through unchanged. --: "end of options" for most commands;./*(instead of*) makes every expanded name start with./, so none can look like an option.set -e: exit when a command fails.set -u: an unset variable is an error.set -o pipefail: a pipeline fails if any stage fails, not only the last.mapfile -d ''/find -print0/xargs -0: pass names separated by NUL bytes, the only byte that can't appear anywhere in a path (/can't appear in a name either, but it is part of every path).
Hostile file names
mkdir case && cd case
printf 'alpha\n' > 'my report.txt'
printf 'beta\n' > '-n'
printf 'gamma\n' > '*'
printf 'delta\n' > normal.txt
echo "== unsafe: for f in \$(ls)"
for f in $(ls); do printf '[%s] ' "$f"; done; echo
echo "== unsafe: unquoted \$f to wc -l"
for f in *; do wc -l $f 2>&1 | head -n 1; done
echo "== safe: ./* and quotes"
for f in ./*; do wc -l -- "$f"; done
echo "== safe: NUL-separated from find"
find . -type f -print0 | sort -z | xargs -0 sha256sum -- | cut -c1-12,65-== unsafe: for f in $(ls)
[*] [-n] [my report.txt] [normal.txt] [-n] [my] [report.txt] [normal.txt]
== unsafe: unquoted $f to wc -l
wc: invalid option -- 'n'
wc: invalid option -- 'n'
wc: my: No such file or directory
1 normal.txt
== safe: ./* and quotes
1 ./*
1 ./-n
1 ./my report.txt
1 ./normal.txt
== safe: NUL-separated from find
ae9a6306a205 ./*
f2c82decdd71 ./-n
b6a98d9ce9a2 ./my report.txt
673953e0ad7f ./normal.txt
The unsafe loops go wrong in several ways at once. $(ls) splits my report.txt into two words and globs the word * into every file name, so the loop runs eight times for four files. In the second loop, the unquoted wc -l $f with f='*' expands the star again, and the expansion includes the file -n, which wc rejects as an unknown option; f='-n' fails the same way, and my report.txt becomes a search for a file called my. Only normal.txt is counted correctly. The safe forms see exactly four files, each once, with its real name.
Failing loudly
By default Bash keeps going after a failed command, treats an unset variable as empty and reports only the last stage of a pipeline. That is how a backup script "succeeds" after writing nothing, and how a typo in a variable name becomes rm -rf /. The session uses echo in place of rm, so nothing is deleted.
echo "== default: unset variable is empty"
bash -c 'TARGET_DIR=/srv/app; echo "would run: rm -rf $TARGT_DIR/"'
echo "== with set -u"
bash -c 'set -u; TARGET_DIR=/srv/app; echo "would run: rm -rf $TARGT_DIR/"' 2>&1; echo "exit $?"
echo "== \${var:?} guard"
bash -c 'echo "would run: rm -rf ${TARGT_DIR:?refusing: TARGT_DIR is empty}/"' 2>&1; echo "exit $?"
echo "== pipeline status without and with pipefail"
bash -c 'grep -c Failed /no/such/log | sort; echo "exit $?"' 2>&1
bash -c 'set -o pipefail; grep -c Failed /no/such/log | sort; echo "exit $?"' 2>&1
echo "== set -e stops at the first failure"
bash -c 'set -euo pipefail; echo step1; cp /no/such/file /tmp/x; echo step2' 2>&1; echo "exit $?"== default: unset variable is empty
would run: rm -rf /
== with set -u
bash: line 1: TARGT_DIR: unbound variable
exit 127
== ${var:?} guard
bash: line 1: TARGT_DIR: refusing: TARGT_DIR is empty
exit 127
== pipeline status without and with pipefail
grep: /no/such/log: No such file or directory
exit 0
grep: /no/such/log: No such file or directory
exit 2
== set -e stops at the first failure
step1
cp: cannot stat '/no/such/file': No such file or directory
exit 1
Without set -u the misspelt $TARGT_DIR silently expands to nothing and the command becomes rm -rf /. (GNU rm refuses a bare / by default, --preserve-root, but rm -rf "$TARGT_DIR"/* has no such protection.) With it, Bash stops with "unbound variable". The ${var:?message} form protects one expansion even in scripts that don't use set -u. The pipeline case shows why pipefail matters for log tools: grep failed on a missing file, but sort succeeded, so without pipefail the pipeline reports success.
How unsafe scripts are detected
- ShellCheck (
shellcheck script.sh) finds nearly every pattern in this lesson: SC2086 (unquoted variable), SC2045 (for f in $(ls)), SC2115 (rm -rf "$var/"without a guard), SC2164 (cdwithout|| exit). Run it in CI on every script. - Review privileged scripts first: anything run by root, cron, systemd units, sudo rules, CI runners. Look for variables built from file names, user input or command output.
- Test with hostile names: create files called
-rf,*,a b,$(id), a name with a newline, and run the script on them in a throwaway directory, as above.
How to write it safely
- Start scripts with
#!/usr/bin/env bashandset -euo pipefail. Know their limits:set -eis ignored insideifconditions and||chains, so check important commands explicitly. - Quote every expansion:
"$var","$@","$(cmd)". Use arrays for lists of arguments:args=(-l -- "$f"); wc "${args[@]}". - Use
./*or--whenever a file name reaches a command. - NUL-separate file lists:
find … -print0 | xargs -0 …, orwhile IFS= read -r -d '' f; do …; done < <(find … -print0). - Guard destructive commands:
"${dir:?}", check the path is inside an expected root, and prefermvto a quarantine directory overrm. - Temporary files with
mktempand atrap 'rm -f "$tmp"' EXIT, never fixed names in/tmp, which another user can pre-create as a symlink.
Pitfalls
echo "$var"misbehaves whenvaris-nor contains backslashes in some shells;printf '%s\n' "$var"is always literal.readwithout-rtreats backslashes as escapes; withoutIFS=it trims spaces.[ $a = $b ]fails or misleads when a variable is empty or has spaces; use[[ "$a" == "$b" ]]in Bash.set -eis not error handling. It stops the script; it doesn't clean up or report. Add atrap … ERRor explicit checks where it matters.
Practice
1. What does rm $f do when f is -rf * (with a space)?
It splits into -rf and *; the star expands to every file in the directory, and rm -rf deletes them all, including directories. rm -- "$f" would try to remove one file literally called -rf *.
2. Rewrite for f in $(find /var/log -name '*.log'); do gzip $f; done safely.
find /var/log -name '*.log' -print0 | xargs -0 -r gzip -- or find /var/log -name '*.log' -exec gzip -- {} +. The -exec … {} + form never goes through the shell's splitting at all.
3. A cron script runs cd /srv/app/tmp; rm -rf * as root. What happens if the directory doesn't exist, and how do you fix it?
cd fails, the script continues in its current directory (often / or root's home for cron) and deletes everything there. Fix: cd /srv/app/tmp || exit 1 (or set -e), and better rm -rf -- /srv/app/tmp/* with an absolute path so no cd is needed.
Test yourself
Which form passes the value of f to a command as exactly one argument?
$f"$f"${f}$(echo $f)
Why does the session use ./* instead of * in the safe loop?
- It is faster
- Every expanded name then starts with ./ and can't be taken as an option, such as the file named -n
- It skips hidden files
- It sorts the files
grep -c Failed /no/such/log | sort returns exit status 0. What makes it return non-zero?
- set -u
- set -o pipefail
- set -x
- Quoting the file name
Which tool reports unquoted variables (SC2086) in shell scripts?
- Bandit
- ShellCheck
- YARA
- Semgrep only