Find and pass filenames safely
find traverses directory trees. Quote its -name pattern so the shell does not expand it before find receives it. -type f selects regular files. Use -exec command {} + to pass batches of path arguments directly; with ; each match starts an invocation. A NUL byte cannot occur in a filename, so find -print0 and xargs -0 preserve boundaries even when names contain newlines. GNU xargs -r avoids executing a command with no input. Prefer -exec for simple work without a pipe. These techniques preserve argument boundaries, not protection against concurrent filesystem changes. Use owned directories; never follow an untrusted tree into destructive operations. A producer failure in process substitution is not automatically the loop status. Example 3 first saves a NUL-delimited list after checking find, then counts that list; a failed traversal must not be reported as a successful count. This uses a disposable directory and does not provide a filesystem snapshot.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Pass files directly
mkdir data || exit 1printf 'abc' > 'data/daily report.txt' || exit 1find data -type f -name '*.txt' -exec wc -c {} +Expected stdout:
3 data/daily report.txtfind passes the complete path as one argument to wc.
Preserve a newline in a filename
mkdir data || exit 1touch -- $'data/line\nbreak.txt' || exit 1find data -type f -print0 | xargs -0 -r printf '[%s]\n'Expected stdout:
[data/linebreak.txt]The brackets enclose one argument despite the embedded newline. -r is a GNU extension also supported by some other implementations.
Read NUL records in Bash
mkdir data || exit 1touch 'data/a b' 'data/c' || exit 1find data -type f -print0 > paths.bin || exit 1count=0while IFS= read -r -d '' path; do count=$((count+1))done < paths.bin || exit 1printf 'files=%s\n' "$count"Expected stdout:
files=2The checked find command writes a NUL-delimited list. Direct redirection keeps the loop in the current shell.
Common mistakes
Never use for f in $(ls) or plain find | xargs for arbitrary filenames. Newlines and quotes are valid name characters. A printed line is not necessarily a single filename.
Practice
Create two text files with spaces and one with a newline in its name. Use find -exec to count their bytes, then compare with a NUL-delimited listing. Explain why line counting the listing is incorrect.
Next: Filter text with grep and cut