When to use xargs when piping?

后端 未结 5 729
挽巷
挽巷 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条回答
  •  忘掉有多难
    2021-02-07 11:53

    Short answer: Avoid xargs for now. Return to xargs when you have written dozens or hundreds of scripts.

    Commands can get their input from parameters (like rm bad_example) or can get the input from stdin (not just the y on the question after rm -i is_this_bad_too, but also read answer). Other commands like grep and sed will look for parameters and when the parameters don't show the input, switch to the input.
    Your grep example works fine reading from stdin, nothing special needed.
    Your ls needs the output of find as a parameter. xargs is just one way to turn things around. Use man xargs for more about xargs. Alternatives:

    find /etc -name "*.txt" -exec ls -l {} \;
    find /etc -name "*.txt" -ls
    ls -l $(find /etc -name "*.txt" )
    ls /etc/*.txt
    

    First try to see which of this commands is best when you have a nasty filename with spaces.txt in /etc.

提交回复
热议问题