About the usage of linux command "xargs"

linux, shell

Solution

`xargs` puts the words coming from the standard input to the end of the argument list of the given command. The first form therefore creates

cp /tmp/ ./useful/love.txt ./useful/loveyou.txt

Which does not work, because there are more than 2 arguments and the last one is not a directory.

The `-i` option tells `xargs` to process one file at a time, though, replacing `{}` with its name, so it is equivalent to

cp ./useful/love.txt    /tmp/
cp ./useful/loveyou.txt /tmp/

Which clearly works well.

Problem

I have some file like ``` love.txt loveyou.txt ``` in directory `useful`; I want to copy this file to directory `/tmp`. I use this command: ``` find ./useful/ -name "love*" | xargs cp /tmp/ ``` but is doesn't work, just says: ``` cp: target `./useful/loveyou.txt' is not a directory ``` when I use this command: ``` find ./useful/ -name "love*" | xargs -i cp {} /tmp/ ``` it works fine, I want to know why the second works, and more about the usage of `-i cp {}`.

Original source