xargs in Linux: build a command from input

Updated November 1, 2026

xargs takes lines from standard input and passes them as arguments to another command.

Syntax

... | xargs [command]

Common cases

echo a b c | xargs mkdir            # create directories a, b, c
find . -name '*.tmp' | xargs rm     # delete every .tmp found
find . -name '*.log' -print0 | xargs -0 rm   # safe with spaces
cat urls.txt | xargs -n1 echo       # one argument at a time
ls | xargs -I{} mv {} {}.bak        # {} stands for the name

Sample output

$ ls
draft.txt
note.txt
$ ls | rm
rm: missing operand
Try 'rm --help' for more information.
$ ls | xargs rm
$ ls

How it works: why xargs when you have a pipe

A pipe | feeds output to the standard INPUT of the next command. But many commands (rm, mkdir, cp) take their targets from ARGUMENTS, not from input. xargs bridges the two: it reads lines and appends them to a command as arguments. The main trap is spaces and newlines in file names. The safe way is find ... -print0 | xargs -0, where names are separated by a null byte, not a space. find -exec often does the same job, but xargs runs the command fewer times and so is faster on big lists.

Common mistakes

Empty input does not stop xargs: the command still runs once, with no arguments. find . -name '*.nomatch' | xargs ls found nothing, yet ls ran and printed the current directory. Put something like rm -rf where ls is and the joke ends. The -r flag (long form --no-run-if-empty) tells xargs to stay quiet when the input is empty.

xargs -I{} changes the parsing rules: it takes a whole line as one argument instead of splitting it on spaces, and runs the command once per line. That is why ls | xargs -I{} cp {} {}.bak copies a file named my report.txt without trouble while ls | xargs cp breaks on it. The price is speed: on a list of thousands of names that is thousands of separate runs.

A single quote inside a file name breaks xargs outright. With a file named it's fine.txt, ls | xargs ls prints xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option and does nothing at all. xargs parses quotes in its input, and ls gave no warning about them. -I{} does not help here; the pair -print0 and -0 does.

In the book

This topic is covered in full in the chapter Streams, redirection, pipelines.

See also

Pipes and filters, The find command, Regular expressions.

Try it

Open the sandbox: a real throwaway Linux terminal in your browser. Run the commands above by hand - the container is deleted when you leave.