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.
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)
Do not use `for file in $(find ...)` for file paths.
Prefer null-delimited pipelines or carefully quoted `read` loops.
Why is find ./logs -print0 | xargs -0 safe for filenames that for f in $(find ./logs) is not?
Show the answer
Correct: B. NUL is the one byte a filename cannot contain, so it is an unambiguous separator
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
- Create files with spaces.
- Count them with `find -print0 | xargs -0`.
- Write a safe loop that prints each path.
Deliverable evidence
- A null-safe command and output.
- One unsafe pattern you avoided.
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.
Commit these to memory, then drill them until recall is automatic.
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