xargs Command Guide for Building Command Lines from Input
This guide helps you understand and use the xargs command, the bridge that turns lines of text into command arguments.
What is xargs, and Why Use It?
The xargs command reads items from standard input and builds command lines from them, running a command with those items as arguments. Many tools produce lists — find outputs file paths, ps outputs processes — but most commands take their input as arguments, not as a stream. xargs translates between the two worlds.
Why Learn xargs?
- The
findpartner:findprints paths; commands likermneed arguments —xargscloses the loop. - Batch operations: Delete, count, or process hundreds of files from a list without typing names.
- Parallelism:
-Pruns several copies of a command at once. - Process control: The classic
ps | grep | awk | xargs killpipeline is built on it.
xargsis the glue between stream-producing commands and argument-consuming ones. If a command “doesn’t read from stdin,”xargsis how you make it.
1. The Basics: Stream to Arguments
By default, xargs splits input on whitespace and appends the pieces to the command:
echo "file1.txt file2.txt" | xargs wc -l
wcreceives both names as arguments and reports line counts for each.
A more realistic example:
find . -name "*.log" | xargs rm
findprints one path per line;xargspasses them tormas arguments.
When no command is given, xargs defaults to echo:
ls | xargs
Just prints the file names — useful for checking what a list actually contains before acting on it.
2. Safe Filenames: -0 with -print0
Splitting on whitespace breaks whenever a file name contains a space or newline. The safe pattern uses null characters as separators, which no file name can contain:
find . -name "*.log" -print0 | xargs -0 rm
-print0—findseparates paths with a null byte instead of a newline.-0—xargsreads null-separated input instead of whitespace-separated.
This pairing is the single most important xargs idiom; use it whenever file names come from untrusted or unknown sources.
3. Controlling Batch Size (-n)
By default xargs packs as many items as fit into one command. -n caps the number of arguments per run:
find . -name "*.jpg" | xargs -n 3 echo
- Runs
echoonce per group of three files, repeatedly, until the input is exhausted.
Why it matters: some commands misbehave when run with too many arguments, and -n lets you control the batch exactly. A common use is feeding a fixed number of items per invocation of an interactive-ish tool:
cat urls.txt | xargs -n 1 curl -s -O
-n 1— one URL percurlrun.
4. Running in Parallel (-P)
-P runs multiple commands at the same time, which speeds up slow per-item work:
cat urls.txt | xargs -P 4 -n 1 curl -s -O
- Up to four
curlprocesses run concurrently.
Parallelism multiplies throughput for I/O-bound tasks like downloads, but be careful with commands that write to the same file or hit the same server — rate limits and races are real.
5. Replacing a Placeholder (-I)
-I STR replaces every occurrence of STR in the command with each input line, and runs the command once per line:
cat hosts.txt | xargs -I {} ssh {} uptime
{}is just a placeholder — any string works (-I NAME).- Each host gets its own
sshinvocation withuptimeappended.
This is the pattern for commands where the input must land in the middle of an argument structure rather than at the end:
cut -d: -f1 /etc/passwd | head -5 | xargs -I USER echo "Home of USER:"
6. Confirm Before Acting (-p and -t)
For destructive operations, make xargs ask first:
find . -name "*.tmp" | xargs -p rm
-ppromptsrm ... ?before each batch; answeryto proceed.
Or trace what would run without running it:
find . -name "*.tmp" | xargs -t rm
-tprints each command to stderr before executing it — a dry run you can eyeball.
7. Real-World Pipelines
xargs is usually the last stage of a filtering pipeline:
ps aux | grep nginx | grep -v grep | awk '{print $2}' | xargs kill
- Extract process IDs, then kill each one.
ls *.txt | xargs -I {} sh -c 'gzip {}'
Compress every text file — though see the pitfalls below for why find ... -exec is often cleaner.
du -sh * | sort -h | tail -3 | cut -f2 | xargs -I {} echo "Largest: {}"
Common Pitfalls
- Whitespace in file names breaks the default mode. Always pair
-print0with-0when names come fromfindor similar tools. - Empty input can still run the command once. With no input, some versions run the command with no arguments; GNU
xargshas-r(or--no-run-if-empty) to prevent that. - Commands that read stdin get starved. A command like
sshinsidexargsmay swallow the remaining input;-Iavoids this by running one item at a time. xargsdoesn’t run a shell. Pipes, globs, and~inside the input aren’t expanded; wrap insh -c '...'if you need shell features — but quote carefully.- Huge lists are split into multiple runs. If the command must run exactly once (e.g., appending to one file), check behavior or feed it a single argument instead.
Related Pages
| Page | Relationship |
|---|---|
find | Produces the file lists xargs consumes — the two are a matched pair. |
grep | Filters input before xargs acts on it. |
awk | Extracts fields (like PIDs) that xargs turns into arguments. |
cut | Slices columns out for xargs input. |
sort | Orders or deduplicates lists before batching. |
xargs Cheatsheet
| Flag | Meaning |
|---|---|
-0 | Read null-separated input (pair with find -print0). |
-n NUM | At most NUM arguments per command run. |
-P NUM | Run up to NUM commands in parallel. |
-I STR | Replace STR in the command with each input line; one run per line. |
-p | Prompt the user before each run. |
-t | Print each command before running it. |
-r | Don’t run the command if input is empty (GNU). |
That completes the Text Processing section — review it all in the section overview, or continue to Git & GitHub.