When to use xargs when piping?

后端 未结 5 540
挽巷
挽巷 2021-02-07 10:59

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

5条回答
  •  梦毁少年i
    2021-02-07 11:54

    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.

提交回复
热议问题