Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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 find partner: find prints paths; commands like rm need arguments — xargs closes the loop.
  • Batch operations: Delete, count, or process hundreds of files from a list without typing names.
  • Parallelism: -P runs several copies of a command at once.
  • Process control: The classic ps | grep | awk | xargs kill pipeline is built on it.

xargs is the glue between stream-producing commands and argument-consuming ones. If a command “doesn’t read from stdin,” xargs is 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
  • wc receives both names as arguments and reports line counts for each.

A more realistic example:

find . -name "*.log" | xargs rm
  • find prints one path per line; xargs passes them to rm as 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 — find separates paths with a null byte instead of a newline.
  • -0 — xargs reads 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 echo once 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 per curl run.

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 curl processes 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 ssh invocation with uptime appended.

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
  • -p prompts rm ... ? before each batch; answer y to proceed.

Or trace what would run without running it:

find . -name "*.tmp" | xargs -t rm
  • -t prints 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: {}"
  • Chains du, sort, cut, and xargs into a “top three” report.

Common Pitfalls

  • Whitespace in file names breaks the default mode. Always pair -print0 with -0 when names come from find or similar tools.
  • Empty input can still run the command once. With no input, some versions run the command with no arguments; GNU xargs has -r (or --no-run-if-empty) to prevent that.
  • Commands that read stdin get starved. A command like ssh inside xargs may swallow the remaining input; -I avoids this by running one item at a time.
  • xargs doesn’t run a shell. Pipes, globs, and ~ inside the input aren’t expanded; wrap in sh -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.

PageRelationship
findProduces the file lists xargs consumes — the two are a matched pair.
grepFilters input before xargs acts on it.
awkExtracts fields (like PIDs) that xargs turns into arguments.
cutSlices columns out for xargs input.
sortOrders or deduplicates lists before batching.

xargs Cheatsheet

FlagMeaning
-0Read null-separated input (pair with find -print0).
-n NUMAt most NUM arguments per command run.
-P NUMRun up to NUM commands in parallel.
-I STRReplace STR in the command with each input line; one run per line.
-pPrompt the user before each run.
-tPrint each command before running it.
-rDon’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.