Skip to content
FLAVIO COPES
flaviocopes.com
2026

Linux commands: xargs

By Flavio Copes

Learn how the Linux xargs command turns the output of one command into arguments for another, like piping cat into rm, plus the handy -p and -n options.

~~~

The xargs command is used in a UNIX shell to convert input from standard input into arguments to a command.

In other words, through the use of xargs the output of a command is used as the input of another command.

Here’s the syntax you will use:

command1 | xargs command2

We use a pipe (|) to pass the output to xargs. That will take care of running the command2 command, using the output of command1 as its argument(s).

Let’s do a simple example. You want to remove some specific files from a directory. Those files are listed inside a text file.

We have 3 files: file1, file2, file3.

In todelete.txt we have a list of files we want to delete, in this example file1 and file3:

Terminal showing ls command with files file1, file2, file3, todelete.txt and cat command displaying todelete.txt contents

We will channel the output of cat todelete.txt to the rm command, through xargs.

In this way:

cat todelete.txt | xargs rm

That’s the result, the files we listed are now deleted:

Terminal after running xargs rm showing file1 and file3 deleted, with only file2 and todelete.txt remaining

The way it works is that xargs will run rm 2 times, one for each line returned by cat.

This is the simplest usage of xargs. There are several options we can use.

One of the most useful in my opinion, especially when starting to learn xargs, is -p. Using this option will make xargs print a confirmation prompt with the action it’s going to take:

Terminal showing xargs -p option with confirmation prompt asking rm file1 file3

The -n option lets you tell xargs to perform one iteration at a time, so you can individually confirm them with -p. Here we tell xargs to perform one iteration at a time with -n1:

Terminal showing xargs -p -n1 option with individual confirmation prompt asking rm file1

The -I option is another widely used one. It allows you to get the output into a placeholder, and then you can do various things.

One of them is to run multiple commands:

command1 | xargs -I % /bin/bash -c 'command2 %; command3 %'

Terminal showing xargs -I option with placeholder running multiple commands ls and rm with confirmation prompt

You can swap the % symbol I used above with anything else, it’s a variable

The xargs command works on Linux, macOS, WSL, and anywhere you have a UNIX environment

Tagged: CLI · All topics
~~~

Related posts about cli: