How to repeat variables twice in xargs

xargs

How can I make the second echo to echo out test in this example as well:

 echo test  | xargs -I {} echo {} && echo {}

Best Answer

Just write {} two times in your command. The following would work:

$ echo test | xargs -I {} echo {} {}
test test

Your problem is how the commands are nested. Lets look at this:

echo test | xargs -I {} echo {} && echo {}

bash will execute echo test | xargs -I {} echo {}. If it runs successfully, echo {} is executed. To change the nesting, you could do something like this:

echo test | xargs -I {} sh -c "echo {} && echo {}"

However, you could get trouble because the approach might be prone to code injection. When "test" is substituted with shell code, it gets executed. Therefore, you should probably pass the input to the nested shell with arguments.

echo test | xargs -I {} sh -c 'echo "$1" && echo "$1"' sh {}
Related Question