我目前有当前脚本。
#!/bin/bash
# script.sh
for i in {0..99}; do
script-to-run.sh input/ output/ $i
done
我希望使用 xargs 并行运行它。我试过了
script.sh | xargs -P8
但是上面的操作一次只执行一次。 -n8 也没有运气。 在循环脚本中要执行的行的末尾添加 & 将尝试一次运行脚本 99 次。我如何一次只执行 8 个循环,总共执行 100 个。
最佳答案
来自xargs
手册页:
This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is /bin/echo) one or more times with any initial- arguments followed by items read from standard input. Blank lines on the standard input are ignored.
这意味着对于您的示例 xargs
正在等待并收集脚本的所有输出,然后运行 echo <that output>
.不是那么有用,也不是您想要的。
-n
参数是输入中有多少项与运行的每个命令一起使用(这里没有关于并行性的内容)。
用xargs
做你想做的事你需要做更多类似这样的事情(未经测试):
printf %s\\n {0..99} | xargs -n 1 -P 8 script-to-run.sh input/ output/
它像这样分解。
-
printf %s\\n {0..99}
- 每行打印一个数字0
至99
. - 运行
xargs
- 每次运行命令行最多一个参数
- 同时运行最多八个进程
关于bash - 使用 xargs 并行运行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28357997/