Safe File Handling with find -print0 and xargs -0

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 112 of 205

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

ProducerConsumer
find ... -print0xargs -0
sort -zsort -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:

StatusMeaning
0every run succeeded
123at least one run returned a status from 1 to 125
124a run returned 255; xargs stopped
126the command was found but could not be run (from the GNU manual; not shown below)
127the 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 sh after the script becomes $0 inside it. The names follow as $1, $2 and so on.
  • for f; do is short for for 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 '' makes read stop at a null byte instead of a newline.
  • IFS= keeps leading and trailing spaces; -r keeps backslashes.
  • < <(...) feeds the loop through process substitution (lesson 151). Unlike a pipe, it keeps the loop in the current shell, so count keeps 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 -z and cut -z treat null bytes as line ends.
  • du --files0-from=- and wc --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 f limits the search to regular files, and -mtime +7 to files last modified more than seven days ago.
  • -print0 and -0 keep each name whole.
  • -r avoids running gzip with no files, which would make it read standard input.
  • -- stops gzip from reading a name that starts with - as an option. find names 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Safe File Handling with find -print0 and xargs -0 and get answers drawn from it.

Signed-in readers only.