Skip to content

xargs command on Linux (execute command as argument)

The xargs command in Linux executes the command or program and passes as an argument to that command what was received as standard input.

It solves the problem of taking the standard output of a program and using it as arguments or parameters for a command or program.

The most common options are:

  • -p: Ask the user if the command should be executed before doing so
  • -r: Don’t execute the command when you receive empty lines
  • -t: Show the command on the screen before executing it

See the supermarket list:

$ cat supermarket
rice
bean
meat
potato
lettuce
tomato
rice
Flesh

Now let’s make xargs receive this list as standard input, and execute the echo command with the items in the list as a parameter:

$ cat supermarket | xargs echo

What xargs does is as if it were writing the following command:

$ echo rice beans meat potato lettuce tomato rice meat

In the same way, you can create directories with the names of the items in the list. In this example the xargs command will create a directory running mkdir with the name of each item contained in the supermarket file:

$ cat supermarket | xargs mkdir

As you can see, xargs can be very useful for automating various tasks.

In this example, all files with a txt extension are listed, and then xargs is used to compress each of them:

$ ls -1 *.txt | xargs gzip

The xargs “-t” option is interesting because it writes the command it will execute:

$ ls -1 *.txt | xargs -t gzip gzip teste1.txt teste2.txt teste3.txt

xargs can also be used to download multiple files from a list of links:

$ cat links.txt | xargs wget

The “-i” option combined with {} can be used to pass arguments at the correct location of a command:

$ ls /etc/ *.conf | xargs -i cp {} /home/learnlinux/conf

Learn much more about Linux in our online course. You can register here. If you already have an account, or want to create one, just log in or create your user here.

Did you like it?

Share