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:
todelete.txt we have a list of files we want to delete, in this example
We will channel the output of
cat todelete.txt to the
rm command, through
In this way:
cat todelete.txt | xargs rm
That’s the result, the files we listed are now deleted:
The way it works is that
xargs will run
rm 2 times, one for each line returned by
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
-p. Using this option will make
xargs print a confirmation prompt with the action it’s going to take:
-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
-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 %'
You can swap the
%symbol I used above with anything else, it’s a variable
xargs command works on Linux, macOS, WSL, and anywhere you have a UNIX environment
Download my free Linux Commands Handbook
More cli tutorials:
- Linux commands: open
- Unix Shells Tutorial
- Linux commands: man
- Linux commands: gzip
- Linux commands: mkdir
- Linux, no space left on device
- Linux commands: grep
- Linux commands: clear
- Linux commands: cat