xargs

On this page 7

xargs is a standard Unix and Linux command that reads items from standard input and turns them into command-line arguments for another program, which it then executes one or more times. It connects tools that produce lists, such as find or grep, with tools that expect file names as arguments, such as rm, gzip or chmod.

In shell work, xargs solves two problems at once: it bridges the gap between a pipe and argument lists, and it splits very long lists into batches that fit within the operating system limit on command length. Modern implementations add parallel execution, which makes xargs a lightweight job runner as well.

How the xargs command builds command lines

The xargs command works by collecting input tokens into an argument buffer and invoking the target command whenever the buffer is full or the input ends. Without a command, it runs /bin/echo, which is a convenient way to see what it would do.

By default, xargs splits input on blanks and newlines and interprets single quotes, double quotes and backslashes. This legacy behavior, defined by POSIX, is why file names containing spaces break naive pipelines. The null-delimited mode with -0 reads items separated by the NUL byte instead, the only character that cannot appear in a Linux path.

Batching is driven by the kernel limit known as ARG_MAX, which covers arguments and environment variables together. On typical Linux systems the effective limit is about 2 MB, or a quarter of the stack size. When a list exceeds it, a direct command fails with the error Argument list too long, while xargs simply runs the command several times.

The table below traces what happens to a short input under different options.

InvocationNumber of command runsArguments per run
xargs rm1All five names
xargs -n 2 rm3Two, two, then one
xargs -I {} rm {}5One name per run
xargs -P 4 -n 1 gzip5, up to 4 at onceOne name per run
Effect of options on the same input of five file names

Key options and what they control

The behavior of xargs is shaped by a small set of options for delimiting, batching and execution. The GNU findutils version found on most Linux distributions supports all of them; BSD and macOS versions share the core set with minor differences.

OptionPurposeTypical use
-0Items separated by NUL bytesSafe handling of any file name
-dCustom single-character delimiterNewline-only splitting in GNU
-n numberMaximum arguments per runCommands that accept few arguments
-L numberMaximum input lines per runLine-oriented records
-I stringReplace a placeholder in the commandArgument in the middle of a command
-P numberRun several processes in parallelCPU-bound batch work
-rDo not run when input is emptyAvoid accidental default actions
-t and -pPrint or confirm each commandDebugging and cautious deletion
Frequently used xargs options

The -I option deserves special care. It implies one input line per command run, which removes the efficiency of batching and can be slow on large lists. When the argument can go at the end, the plain form is much faster than running one process per item.

Comparison with find -exec, loops and command substitution

Several shell constructs overlap with xargs, and choosing between them depends on safety with unusual names, process count and parallelism. The following table compares the common alternatives.

TechniqueBatchingParallelismHandles any file name
xargs -0YesYes, with -PYes
find -exec with +YesNoYes
find -exec with semicolonNo, one process per fileNoYes
while read loopNoManual onlyOnly with careful quoting
Command substitutionNo, single commandNoNo, word splitting applies
GNU parallelYesYes, advancedYes
xargs against related shell techniques

For simple file operations, find -exec ... {} + is often the cleanest choice because it needs no pipe. xargs remains preferable when input comes from a program other than find, when parallel execution is required, or when the list must be filtered with grep, sort or awk first.

Using xargs safely in Linux pipelines

Safe use of xargs in Linux depends on pairing a null-terminated producer with a null-aware consumer. The canonical pattern is find . -name '*.log' -print0 | xargs -0 gzip, which works for names with spaces, quotes or newlines.

  • Use grep -lZ, find -print0 or sort -z so that every stage of the pipeline speaks NUL.
  • Add -r in GNU xargs when the input may be empty, so that a command such as ls does not run without arguments.
  • Insert -- before the arguments when names may begin with a hyphen and be mistaken for options.
  • Choose -P from the number of cores for CPU work, but keep it low for disk-bound tasks.
  • Check the exit status: GNU xargs returns 123 when any invocation failed, and 127 when the command was not found.

Parallel runs interleave their output, so commands that print results should write to separate files or use line-buffered output. The order of completion is not guaranteed under -P.

Common mistakes and their fixes

Most xargs failures come from mismatched delimiters and unexpected empty input, and they can be destructive when the target command deletes or moves files.

SymptomCauseFix
File not found for names with spacesDefault blank splittingUse -print0 with xargs -0
Unmatched quote errorApostrophe in a file nameUse -0 or -d with a newline
Command runs on the current directoryEmpty input with no -rAdd -r or test input first
Very slow processing-I starts one process per itemAppend arguments at the end instead
Jumbled outputParallel processes share the terminalWrite per-item output files
Symptoms, causes and fixes

The short version

xargs is a helper that turns a list into a command. One program prints a list of things, such as file names. xargs hands that list to another program. The effect is the same as typing every name by hand.

It also splits very long lists into manageable portions. A command is never given more than the system can accept. It can even run several copies at once to finish sooner.

Where it makes a difference

A system administrator must compress about 200,000 old log files spread across nested directories on a Linux server with eight cores. Running gzip *.log fails immediately with an argument-length error, and a loop that compresses one file at a time would take hours.

The administrator runs find /var/log/app -name '*.log' -mtime +30 -print0 | xargs -0 -r -P 6 -n 100 gzip. find selects only files older than 30 days, xargs passes 100 names to each gzip process and keeps six of them running in parallel, leaving capacity for the production service. Names containing spaces are handled correctly, and the job finishes in minutes rather than hours with no failed files.