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:
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:
What xargs does is as if it were writing the following command:
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:
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:
The xargs “-t” option is interesting because it writes the command it will execute:
xargs can also be used to download multiple files from a list of links:
The “-i” option combined with {} can be used to pass arguments at the correct location of a command:
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