Using xargs to run multiple commands

Viewed 331

Using this post as a starting point I am running the following in bash:

seq 1 5 | xargs -d $'\n' sh -c 'for arg do echo $arg; done'

Expected output

1
2
3
4
5

Actual output

2
3
4
5

i.e. is missing the first of the intended arguments.

Am probably being a tool, but wondering why this is.

3 Answers

You have to pass some dummy value at position 0 to sh script like this:

seq 1 5 | xargs -d $'\n' sh -c 'for arg do echo $arg; done' _
1
2
3
4
5

Without passing _ to sh script 1 is passed as $0 whereas for arg loops through positional arguments starting with position 1 only.

In conclusion, do you want to list number or execute command by row? Usually, use below command in bash.

seq 1 5 | xargs -n 1 -I {} echo {}

Output

1
2
3
4
5

The problem lies with your inline bash code.

seq 1 5 | xargs -n echo produces the desired result. It can also be simplified to seq 5 | xargs -n echo because seq assumes the range starts at 1.

Related