How to use xargs
to build and run a command list such as these:
#1
cmd1 <arg1> && cmd2 <arg1> && cmd3 <arg1>
#2
cmd1 <arg1> ; cmd2 <arg1>
How to use xargs
to build and run a command list such as these:
#1
cmd1 <arg1> && cmd2 <arg1> && cmd3 <arg1>
#2
cmd1 <arg1> ; cmd2 <arg1>
By starting a child shell for each line of input to xargs
:
xargs -I {} sh -c 'cmd1 "$1" && cmd2 "$1" && cmd3 "$1"' sh {}
xargs -I {} sh -c 'cmd1 "$1"; cmd2 "$1"' sh {}
This runs sh -c
which executes the given string as a shell script. The arguments to sh -c
, after the script itself, are given to $0
and $1
inside the script. The value of $0
should usually be the name of the shell, which is why we pass sh
as this argument (it will be used in error messages).
Alternatively,
xargs sh -c '
for arg do
cmd1 "$arg" && cmd2 "$arg" && cmd3 "$arg"
done' sh
xargs sh -c '
for arg do
cmd1 "$arg"
cmd2 "$arg"
done' sh
These variations will take as many arguments as possible and then apply the code to these in a loop inside the sh -c
scripts.
As always when using xargs
, care must be taken so that the arguments supplied to the given utility (sh -c
here) are delimited properly.