简体   繁体   English

使用 xargs 运行多个命令

[英]Using xargs to run multiple commands

Using this post as a starting point I am running the following in bash:使用这篇文章作为起点,我在 bash 中运行以下内容:

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

Expected output预期 output

1
2
3
4
5

Actual output实际 output

2
3
4
5

ie is missing the first of the intended arguments.即缺少第一个预期的 arguments。

Am probably being a tool, but wondering why this is.我可能是一个工具,但想知道为什么会这样。

You have to pass some dummy value at position 0 to sh script like this:您必须将 position 0 处的一些虚拟值传递给sh脚本,如下所示:

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.不将_传递给sh脚本1作为$0传递,而for arg循环通过位置 arguments 仅从 position 1开始。

In conclusion, do you want to list number or execute command by row?总之,您是要列出数字还是逐行执行命令? Usually, use below command in bash.通常,在 bash 中使用以下命令。

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

Output Output

1
2
3
4
5

The problem lies with your inline bash code.问题在于您的内联 bash 代码。

seq 1 5 | xargs -n echo seq 1 5 | xargs -n echo produces the desired result. seq 1 5 | xargs -n echo产生所需的结果。 It can also be simplified to seq 5 | xargs -n echo也可以简化为seq 5 | xargs -n echo seq 5 | xargs -n echo because seq assumes the range starts at 1. seq 5 | xargs -n echo因为seq假定范围从 1 开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM