When to use xargs when piping?

后端 未结 5 555
挽巷
挽巷 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:59

    To answer your question, xargs can be used when you need to take the output from one command and use it as an argument to another. In your first example, grep takes the data from standard input, rather than as an argument. So, xargs is not needed.

    xargs takes data from standard input and executes a command. By default, the data is appended to the end of the command as an argument. It can be inserted anywhere however, using a placeholder for the input. The traditional placeholder is {}; using that, your example command might then be written as:

    find /etc -name "*.txt" | xargs -I {} ls -l {}
    

    If you have 3 text files in /etc you'll get a full directory listing of each. Of course, you could just have easily written ls -l /etc/*.txt and saved the trouble.

    Another example lets you rename those files, and requires the placeholder {} to be used twice.

    find /etc -name "*.txt" | xargs -I {} mv {} {}.bak
    

    These are both bad examples, and will break as soon as you have a filename containing whitespace. You can work around that by telling find to separate filenames with a null character.

    find /etc -print0 -name "*.txt" | xargs -I {} -0 mv {} {}.bak
    

    My personal opinion is that there are almost always alternatives to using xargs, and you will be better served by learning those.

提交回复
热议问题