ch09/l02

Loops, find, and xargs

Use null-safe file lists when automation touches filenames.

xargs -0 25 min read, 35 min lab operator

Filenames can contain spaces, newlines, and leading dashes. Null-delimited output from `find -print0` and `xargs -0` handles names safely.

In the field

You need to count lines in every `.log` file under a copied tree, including files with spaces.

Worked command

$ find ./logs -type f -name '*.log' -print0 | xargs -0 wc -l$ while IFS= read -r -d '' file; do  printf '%s\n' "$file"done < <(find ./logs -type f -print0)
Anti-pattern

Do not use `for file in $(find ...)` for file paths.

Safer pattern

Prefer null-delimited pipelines or carefully quoted `read` loops.

Knowledge check

Why is find ./logs -print0 | xargs -0 safe for filenames that for f in $(find ./logs) is not?

  • A xargs runs faster, so the filenames are processed before they can break
  • B NUL is the one byte a filename cannot contain, so it is an unambiguous separator
  • C -print0 strips spaces and newlines out of the filenames first
  • D xargs -0 quotes every filename in double quotes automatically
Show the answer

Correct: B. NUL is the one byte a filename cannot contain, so it is an unambiguous separator

Why

A filename may hold spaces and newlines but never a NUL byte, so NUL-delimiting separates names unambiguously. The strip-characters answer is wrong: -print0 changes the delimiter, it never alters the names themselves.

Practice checklist

  1. Create files with spaces.
  2. Count them with `find -print0 | xargs -0`.
  3. Write a safe loop that prints each path.

Deliverable evidence

  • A null-safe command and output.
  • One unsafe pattern you avoided.
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.

find -print0xargs -0IFS= read -rwhile loop
Recall practice · Scenario -> next check

cue Produce a null-delimited file list and consume it null-safely to count lines per file

show recall target

find ./logs -type f -print0 | xargs -0 wc -l