ch09/l01

Variables and quoting

Keep data intact as it moves through the shell.

"$var" 20 min read, 25 min lab operator

Variables are text. Unquoted variables can split on spaces and expand globs. Quoting is the default posture unless you deliberately want splitting.

In the field

A backup path includes a space and your script must not split it into two arguments.

Worked command

$ target="/tmp/td script/output file.txt"$ mkdir -p "$(dirname "$target")"$ printf '%s\n' "hello" > "$target"
Anti-pattern

Do not write `$target` unquoted in file operations.

Safer pattern

Quote variables and command substitutions that represent paths or data.

Knowledge check

You run rm $files where files="a.txt b.txt". On a standard bash shell, what actually happens?

  • A rm receives one argument, the literal string "a.txt b.txt"
  • B rm receives two arguments because the value is split on whitespace
  • C rm errors because variables cannot be used as arguments unquoted
  • D rm receives the value unchanged but globs in it are left literal
Show the answer

Correct: B. rm receives two arguments because the value is split on whitespace

Why

Unquoted expansion undergoes word splitting on IFS whitespace, so the shell hands rm two separate arguments. The 'one literal string' answer is exactly what quoting (rm "$files") would give you, which is why it tempts — but unquoted is the unsafe default.

Practice checklist

  1. Create a variable containing spaces.
  2. Use it safely with `mkdir`, `printf`, and `cat`.
  3. Repeat once unquoted in a harmless echo and explain the difference.

Deliverable evidence

  • A quoted variable transcript.
  • A note explaining word splitting.
Teaching diagramch09 · mental model
three layers of safe automation data "$var" quote to keep intact iteration find -print0 | xargs -0 null-delimited names action set -euo pipefail check, print, fail closed leak: word splitting + glob expansion silently corrupt arguments before the action runs exit nonzero, leave evidence

shows: The three safety layers of small shell automation — quoting data, null-safe iteration, and guarded action — and how unquoted or unsplit input leaks corruption into the action stage.

does not prove: It is a model, not a guarantee: set -euo pipefail and quoting reduce common failure classes but do not prove a given script is correct or safe on every input.

Memorize this

Commit these to memory, then drill them until recall is automatic.

"$var"word splittingcommand substitutiondirname
Recall practice · Meaning -> command

cue A path variable may contain spaces; you must pass it to a command as a single intact argument

show recall target

"$var"