2

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>

1 Answer 1

5

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.

3
  • I'm actually using this method, but I wonder if there's any other ways that are more xargs native. Commented Mar 14, 2019 at 11:59
  • 1
    @TranTriet No, not really. This is a fairly common way of doing it. What are your issues with this way of doing it? Commented Mar 14, 2019 at 12:03
  • @TranTriet See updated answer. Commented Mar 14, 2019 at 12:08

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.