What exactly is xargs
?
How do you use it?
When would it be considered pragmatic, or otherwise appropriate to do so?
What exactly is xargs
?
How do you use it?
When would it be considered pragmatic, or otherwise appropriate to do so?
xargs takes input from its standard input to build commands with that input as arguments. It is very useful, when the following command can take only limited number of arguments and you have a large number of arguments to process.
The input is normally delimited by blanks. Since xargs has to process filenames very often, there is a -0
switch which reads the input null-byte delimited. So, even filenames with newlines and spaces are processed correctly.
However, under most kernels the number of characters in a command (and its arguments and parameters) is limited. In those cases, xargs splits the arguments and does multiple executions of the built command to avoid such errors. It's also possible to specify how many arguments each call should have.
Typical use of xargs
is with a pipe and as a replacement for a loop.
Let's consider an example where you have a script where at some point a program prints out a list of files which you should remove. You could write a loop:
for i in $(program); do
rm ${i}
done
But you could also write a one liner with xargs:
program | xargs rm