I am new to bash and I am trying to understand the use of xargs
, which is still not clear for me. For example:
history | grep ls
H
When you use piping without xargs
, the actual data is fed into the next command. On the other hand, when using piping with xargs
, the actual data is viewed as a parameter to the next command. To give a concrete example, say you have a folder with a.txt
and b.txt
. a.txt
contains just a single line 'hello world!', and b.txt
is just empty.
If you do
ls | grep txt
you would end up getting the output:
a.txt
b.txt
Yet, if you do
ls | xargs grep txt
you would get nothing since neither file a.txt nor b.txt contains the word txt.
If the command is
ls | xargs grep hello
you would get:
hello world!
That's because with xargs
, the two filenames given by ls
are passed to grep
as arguments, rather than the actual content.