Overview
xargs reads words from standard input and runs a command with them as arguments. It starts as many runs as it needs to stay under the system's argument-length limit. By default words are split on blanks and newlines, so names with spaces need -0.
Background
The xargs utility appeared in PWB Unix, the Programmer's Workbench, according to the FreeBSD and macOS manuals. It builds command lines from its input. Today the name covers GNU xargs from the findutils package, the xargs that macOS ships, and the xargs applet in BusyBox. They agree on -n, -I, -0, and -r, and differ on parallel runs with -P and the -d delimiter.
Examples
Pass every input line to one command call:
printf 'a\nb\n' | xargs echo
Run the command with at most two arguments each time:
printf 'a\nb\nc\n' | xargs -n 2 echo
Run the command once for each input item by putting it in a {} placeholder:
printf 'one\ntwo\n' | xargs -I {} echo item-{}
Read null-separated items so a space stays inside one name; the null separator is what find -print0 produces:
printf 'a b\0c\0' | xargs -0 -n 1 echo
Run wc on the files named on standard input:
printf 'app.log\nnotes.txt\n' | xargs wc -l
Do nothing when the input is empty, instead of running the command once with no arguments:
printf '' | xargs -r echo ran; echo finished
Options
-n
Use at most this many arguments per command run.
-I
Replace the given string, such as {}, with each input item and run the command once per item. Input
is split on newlines only.
-0
Split input on null bytes instead of blanks and newlines. Use it with find -print0.
-r
Skip the command when the input is empty. GNU runs the command once with no arguments without -r;
BSD does not run it.
Common mistakes
Without -0, a name with a space becomes two arguments. Without -r, GNU xargs runs the command once with no arguments for empty input, so find ... | xargs rm can run a bare rm. xargs runs the program directly, not through a shell, so pipes and redirections in the command do not work unless you run sh -c.
Portability
The Common examples use -n, -I, -0 and -r. Parallel runs with -P and the line-based -d delimiter are not portable. The Common examples were executed on GNU findutils 4.10.0, macOS system tools, and BusyBox 1.37.0 (see the development guide for the exact check).
About macOS xargs
This is the xargs in /usr/bin on macOS. It does not run the command for empty input and accepts -r silently. It has no -d, so convert the delimiter with tr first.
Apple notes
macOS xargs is the BSD implementation. It does not run the command for empty input and it accepts -r silently. It has no -d; convert the delimiter with tr first.
References
Original explanations, with upstream documentation for further reading. FreeBSD references are comparison material, not a claim of Apple version equivalence.