How to use the Linux xargs command
With Linux xargs you convert standard inputs into commands and use them directly. xargs is not used all that often in Linux, but it can greatly simplify processes.
What is the Linux xargs command?
xargs (“extended arguments”) is one of the Linux commands users rarely or never use. However, the command can greatly simplify working and may even help with your computing performance. Put simply, Linux xargs connects two commands, evaluating the output of one and applying the findings to the second. This is useful when processing a large number of files and performing certain tasks over and over again.
xargs is part of most Linux distributions such as Debian or Ubuntu, and doesn’t need to be installed.
How does xargs work?
xargs reads data from stdin (i.e. standard input) and converts it to command lines. The corresponding command must be supplied to the command as a parameter or argument. The respective commands are then executed once or several times. If you do without a special command as parameter, xargs automatically uses the Linux echo command.
What is the syntax of Linux xargs?
To use the xargs command in the terminal, use the following syntax:
$ First_command | xargs [Options] [Second_command]
bashThis causes the second command to be executed with the arguments of the first one.
Which options are available for the xargs command?
There are numerous options for using Linux xargs. These are the most important ones:
- -0 or –null: This option causes each character to be taken literally and arguments to be separated because of the NULL character.
- -a or –arg-file: With this option, arguments aren’t read from standard input, but from a file.
- -d or –delimiter: Separations are made with this option based on the separator character and not the space character. Each character is treated literally.
- -p or –interactive: This option queries whether to continue before executing each command.
Examples for using Linux xargs
The functionality of the xargs command is best shown with some examples.
$ find -name "*.txt" | xargs rm
bashIn this example, you apply xargs with the Linux find command and the Linux rm command. The result is that all files with the extension .txt are removed from the computer’s file system.
$ find -name "*.txt" | xargs grep "invoice"
bashFind all files containing the word “invoice”. For this, you can also use the Linux grep command.