ch03/l03

Quoting and shell expansion

Prevent the shell from changing your command before the program sees it.

printf '%s\n' ./*.log 25 min read, 30 min lab foundation

The shell expands globs, variables, command substitutions, and quotes before launching a command. Good operators know whether they want expansion now, later, or not at all.

In the field

A filename contains spaces and a cleanup glob might match more files than expected.

Worked command

$ touch "app error.log"$ printf '%s\n' ./*.log$ grep -n "ERROR" "app error.log"$ find . -type f -name '*.log' -print0
Anti-pattern

Do not loop over `$(ls)` or unquoted file names.

Safer pattern

Quote variables and paths unless you intentionally need word splitting.

Knowledge check

A file is named `app error.log`. What does `grep -n ERROR app error.log` (unquoted) actually do?

  • A Searches the single file 'app error.log' for ERROR
  • B Searches the file 'app' for the pattern 'error.log'
  • C Searches files 'app' and 'error.log' for the pattern ERROR
  • D Fails immediately because the filename contains a space
Show the answer

Correct: C. Searches files 'app' and 'error.log' for the pattern ERROR

Why

The shell word-splits on the space before grep runs, so grep sees pattern `ERROR` and two filenames, `app` and `error.log`. Quoting as `"app error.log"` keeps it one argument — without quotes the program never sees the name you intended.

Practice checklist

  1. Create files with spaces in names.
  2. Search them with quoted paths.
  3. Preview glob expansion with `printf` before acting.

Deliverable evidence

  • A quoted command that handles a space safely.
  • A note explaining what the shell expanded.
Teaching diagramch03 · mental model
three streams, redirected separately stdin fd 0 command grep / sort stdout fd 1 > file stderr fd 2 2> file stdout pipes to next stage; stderr stays on screen > redirects fd1 only — fd2 needs its own 2>

shows: A command reads stdin (fd0) and writes two independent outputs — stdout (fd1) and stderr (fd2) — each redirectable on its own, so `>` captures data while `2>` captures diagnostics.

does not prove: It shows the wiring of the three streams, not that any given command actually sends errors to stderr — a few tools misroute diagnostics to stdout, so you still confirm by inspecting both targets.

Memorize this

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

quotesglobsvariablesword splittingprintf
Recall practice · Risky -> safer

cue Reference a variable holding a filename that may contain spaces, safely

show recall target

"$file"