Xargs Command – How to Pass Multiple Parameters via Xargs

xargs

I'd like to be able to use xargs to execute multiple parameters in different parts of a command.

For example, the following:

echo {1..8} | xargs -n2 | xargs -I v1 -I v2 echo the number v1 comes before v2

I would hope that it would return

the number 1 comes before 2
the number 3 comes before 4 

… etc

Is this achievable? I suspect that my multiple use of -I is incorrect.

Best Answer

I believe that you can’t use -I that way.  But you can get the effect / behavior you want by saying:

echo {1..8} | xargs -n2 sh -c 'echo "the number $1 comes before $2"' sh

This, essentially, creates an ad hoc one-line shell script, which xargs executes via sh -c.  The two values that xargs parses out of the input are passed to this “script”.  The shell then assigns those values to $1 and $2, which you can then reference in the “script”.

Related Question