Safe File Handling with find -print0 and xargs -0
find locates files and xargs turns a list into command arguments. Together they process thousands of files with a single pipeline. By default, though, both tools separate names with whitespace: find prints one name per line, and xargs splits its input at spaces, tabs and newlines. A filename with a space, a quote or a newline then breaks into pieces or stops xargs with an error.
The fix is to separate names with the null byte, the character with code 0, written \0. It is the one character that can never appear in a Linux or macOS filename, so a list separated by null bytes can carry every possible name without ambiguity. find -print0 writes such a list, and xargs -0 reads it.
The Sample Folder
The examples use this tree, which contains a name with spaces and a name with a newline (shown here as weird⏎name.log):
mkdir -p "logs/old logs" docs
printf 'a\nb\n' > "logs/app.log"
printf 'x\n' > "logs/old logs/error 1.log"
printf 'one\ntwo\nthree\n' > "logs/$(printf 'weird\nname.log')"
printf 'hi\n' > docs/readme.txt
find with its default output (-print) shows the newline name on two lines:
find . -name '*.log' | sort
./logs/app.log
./logs/old logs/error 1.log
./logs/weird
name.log
A reader of this output cannot tell whether the last two lines are one file or two. A script cannot tell either.
The Problem with a Plain Pipe to xargs
xargs reads words from standard input and appends them as arguments to a command. Without options it splits on any whitespace:
find . -name '*.log' | sort | xargs wc -l
2 ./logs/app.log
wc: ./logs/old: No such file or directory
wc: logs/error: No such file or directory
wc: 1.log: No such file or directory
wc: ./logs/weird: No such file or directory
wc: name.log: No such file or directory
2 total
Only app.log survived. ./logs/old logs/error 1.log became three arguments, and the newline name became two. xargs returned status 123, which means at least one run of the command failed.
Plain xargs also treats quotes and backslashes in its input as special characters. A filename with an apostrophe stops it completely:
printf "it's.log\n" | xargs echo
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option
The message itself points to the solution.
Null-Separated Lists
-print0 tells find to write each name followed by a null byte instead of a newline. od -c makes the invisible character visible:
find logs -maxdepth 1 -name 'app.log' -print0 | od -c
0000000 l o g s / a p p . l o g \0
0000015
xargs -0 (long form --null) splits its input only at null bytes and treats every other character, including spaces, quotes, backslashes and newlines, as part of the name:
find . -name '*.log' -print0 | sort -z | xargs -0 wc -l
2 ./logs/app.log
1 ./logs/old logs/error 1.log
3 './logs/weird'$'\n''name.log'
6 total
All three files were counted. wc received exactly three arguments, and GNU wc printed the newline name in a quoted form so that it fits on one output line.
sort -z sorts a null-separated list and writes it back with null separators. It is used here only to give the examples a predictable order; find itself lists entries in the order the file system returns them.
How the Two Sides Fit Together
| Producer | Consumer |
|---|---|
find ... -print0 | xargs -0 |
sort -z | sort -z, xargs -0 |
grep -lZ (--null) | xargs -0 |
printf '%s\0' "${arr[@]}" | xargs -0, read -d '', mapfile -d '' |
Both ends of the pipe must agree. find -print0 | xargs (without -0) treats the null bytes as ordinary characters, and find | xargs -0 reads the whole newline-separated list as one huge name.
Useful xargs Options
Running Once per File with -n 1
By default xargs puts as many names as fit on one command line, which is efficient. -n 1 runs the command once per name:
find . -name '*.log' -print0 | sort -z | xargs -0 -n 1 echo arg:
arg: ./logs/app.log
arg: ./logs/old logs/error 1.log
arg: ./logs/weird
name.log
Each echo received one complete name. The third name prints over two lines only because it contains a newline. -n 2 would pass two names per run:
printf '%s\0' 1 2 3 4 5 | xargs -0 -n 2 echo
1 2
3 4
5
Placing the Name with -I
-I{} replaces {} in the command with each name and runs the command once per name. This is useful when the name must appear in the middle of the arguments:
find . -name '*.log' -print0 | sort -z | xargs -0 -I{} echo "file <{}>"
file <./logs/app.log>
file <./logs/old logs/error 1.log>
file <./logs/weird
name.log>
A typical use is copying each file into a target folder: xargs -0 -I{} cp -- {} "backup/". GNU cp and mv also offer -t DIR, which takes the destination first, so plain xargs -0 cp -t backup/ -- can pass many files per run.
Seeing the Commands with -t
-t prints each command to standard error before running it:
find docs -name '*.txt' -print0 | xargs -0 -t wc -c
wc -c docs/readme.txt
3 docs/readme.txt
Empty Input with -r
When find matches nothing, GNU xargs still runs the command once, with no file arguments:
find . -name '*.pdf' -print0 | xargs -0 wc -l
0
wc received no file name, read its own standard input (which was empty) and printed 0. With commands such as rm -f or chmod this is harmless, but with others it can do the wrong thing or wait for input. -r (--no-run-if-empty) skips the command when there is no input:
find . -name '*.pdf' -print0 | xargs -0 -r wc -l
This prints nothing. According to their manual pages, FreeBSD and macOS xargs do not run the command on empty input in the first place, and accept -r for compatibility with GNU scripts.
Reading the List from a File
-a FILE (GNU) reads the list from a file instead of standard input, which leaves standard input free for the command:
find docs -type f -print0 > list.bin
xargs -0 -a list.bin wc -c
3 docs/readme.txt
Running in Parallel with -P
-P N runs up to N commands at the same time, which speeds up slow work such as compressing files: find . -name '*.log' -print0 | xargs -0 -P 4 -n 1 gzip. The output of parallel jobs can appear in any order.
Exit Status of xargs
xargs reports the outcome of the commands it ran:
| Status | Meaning |
|---|---|
| 0 | every run succeeded |
| 123 | at least one run returned a status from 1 to 125 |
| 124 | a run returned 255; xargs stopped |
| 126 | the command was found but could not be run (from the GNU manual; not shown below) |
| 127 | the command was not found |
printf 'nofile\0' | xargs -0 wc -l; echo "status $?"
printf 'a\0' | xargs -0 sh -c 'exit 255'; echo "status $?"
printf 'a\0' | xargs -0 nosuchcmd; echo "status $?"
wc: nofile: No such file or directory
status 123
xargs: sh: exited with status 255; aborting
status 124
xargs: nosuchcmd: No such file or directory
status 127
Lesson 116 covers exit codes in general.
Running Several Commands per File
xargs runs a single program, not a shell command line, so pipes, redirections and $(...) cannot appear directly in its arguments. Wrapping the work in sh -c (or bash -c) passes the names to a small script as positional parameters:
find . -name '*.log' -print0 | sort -z |
xargs -0 sh -c 'for f; do printf "%s has %s lines\n" "$f" "$(wc -l < "$f")"; done' sh
./logs/app.log has 2 lines
./logs/old logs/error 1.log has 1 lines
./logs/weird
name.log has 3 lines
- The single-quoted string is the script. The names never become part of the script text, so special characters in them cannot be run as code.
- The
shafter the script becomes$0inside it. The names follow as$1,$2and so on. for f; dois short forfor f in "$@"; do.
Never build the command by inserting a name into the script string, as in sh -c "wc -l {}" with -I{}. A file named x; rm -rf ~ would then be run as commands. Lesson 155 covers command injection in detail.
The Alternative: find -exec
find can run commands itself, which avoids the pipe entirely. -exec command {} + collects many names into one command line, like xargs:
find . -name '*.log' -exec wc -l {} +
3 './logs/weird'$'\n''name.log'
1 ./logs/old logs/error 1.log
2 ./logs/app.log
6 total
The order is the order in which find met the files, which depends on the file system. -exec command {} \; runs the command once per name; the \; (or ';') ends the command and must be escaped so that Bash does not treat it as its own command separator:
find . -name '*.log' -exec echo "one:" {} \;
Each name is passed as a single argument, with no splitting at any stage. Prefer -exec ... {} + when the job is simple; use -print0 | xargs -0 when you need xargs options such as -P, -n or -r, or when the list passes through other tools such as sort -z or grep -lZ on the way.
For deleting, GNU and BSD find also offer -delete, which removes matches without starting any other program:
find . -name '*.tmp' -delete
Reading a Null-Separated List in Bash
When each file needs several shell commands, a while loop can read the list directly. read -d '' sets the line delimiter to the null byte:
count=0
while IFS= read -r -d '' f; do
count=$((count + 1))
printf '[%q]\n' "$f"
done < <(find . -name '*.log' -print0 | sort -z)
echo "count=$count"
[./logs/app.log]
[./logs/old\ logs/error\ 1.log]
[$'./logs/weird\nname.log']
count=3
-d ''makesreadstop at a null byte instead of a newline.IFS=keeps leading and trailing spaces;-rkeeps backslashes.< <(...)feeds the loop through process substitution (lesson 151). Unlike a pipe, it keeps the loop in the current shell, socountkeeps its value after the loop.printf '%q'prints each name in a form that can be pasted back into the shell, which shows the space and newline clearly.
mapfile -d '' (Bash 4.4 or later) reads the whole list into an array in one step:
mapfile -d '' -t logs < <(find . -name '*.log' -print0 | sort -z)
echo "${#logs[@]}"
3
-t removes the null byte from the end of each element. The array can then be passed safely to any command with "${logs[@]}".
Both read -d and mapfile are Bash features. Dash rejects the option:
dash: 1: read: Illegal option -d
Where -print0 Goes in the find Expression
find evaluates its expression from left to right, and actions such as -print0 run when they are reached. -print0 therefore belongs at the end, after the tests:
find . -name '*.log' -print0 | tr '\0' '\n' | wc -l
find . -print0 -name '*.log' | tr '\0' '\n' | wc -l
4
9
The first command lists the three .log files (four lines, because one name contains a newline). The second prints every entry before the -name test is checked, so all eight entries appear. tr '\0' '\n' turns null bytes into newlines, which is a handy way to look at a null-separated list.
With -o (or), the tests must be grouped in escaped parentheses, because the action binds only to the test right before it:
find . \( -name '*.log' -o -name '*.txt' \) -print0 | sort -z | tr '\0' '\n'
./docs/readme.txt
./logs/app.log
./logs/old logs/error 1.log
./logs/weird
name.log
Without the parentheses, find . -name '*.log' -o -name '*.txt' -print0 printed only ./docs/readme.txt.
Other Tools That Speak Null
Several GNU tools can read or write null-separated data:
grep -lZ(or--files-with-matches --null) prints matching filenames followed by null bytes:
grep -rlZ 'two' . | xargs -0 printf 'match: %q\n'
match: './logs/weird'$'\n''name.log'
sort -z,uniq -z,head -z,tail -zandcut -ztreat null bytes as line ends.du --files0-from=-andwc --files0-from=-read a null-separated list of files from standard input.tar --null -T -reads a null-separated list of files to archive.printf '%s\0' "${arr[@]}"turns a Bash array into a null-separated list.
A Complete Example
This script compresses every .log file older than seven days under a folder given as an argument, handling every possible filename:
#!/usr/bin/env bash
dir=${1:?usage: compress-old-logs.sh DIR}
find "$dir" -type f -name '*.log' -mtime +7 -print0 |
xargs -0 -r gzip --verbose --
"$dir"is quoted, so a folder name with spaces works.-type flimits the search to regular files, and-mtime +7to files last modified more than seven days ago.-print0and-0keep each name whole.-ravoids runninggzipwith no files, which would make it read standard input.--stopsgzipfrom reading a name that starts with-as an option.findnames start with the folder path, so this matters mostly when the list comes from elsewhere, but it costs nothing.
Run on a folder named old dir holding a b.log and c.log (both dated 1 November 2026) and a new new.log, it compressed only the two old files:
bash compress-old-logs.sh "old dir"
old dir/a b.log: -40.0% -- replaced with old dir/a b.log.gz
old dir/c.log: -40.0% -- replaced with old dir/c.log.gz
A second run found nothing to do, printed nothing and returned status 0, because -r skipped gzip. Run without an argument, the script stops at the ${1:?...} check (lesson 45) with status 1.
The examples were run with Bash 5.2.21, GNU findutils 4.9.0 (find, xargs), GNU coreutils 9.4, GNU grep 3.11 and Dash.