bash - 使用 xargs 并行运行程序

标签 bash parallel-processing xargs

我目前有当前脚本。

#!/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} - 每行打印一个数字 099 .
  • 运行 xargs
    • 每次运行命令行最多一个参数
    • 同时运行最多八个进程

关于bash - 使用 xargs 并行运行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28357997/

相关文章:

linux - 如何将一些文件从dos格式转换成unix格式

multithreading - QML:在并行线程中运行函数

bash - gnu并行中的两对双引号冲突

bash - 如何从使用 xargs 运行的脚本中提示用户

bash - 如何使用shell脚本在文本文件中添加一个空行?

linux - 使用 Bash 检测网关/路由器 : Functions and Variables.

c - 我想使用 OpenMP 并行化 C 代码片段,但得到错误的输出

xargs - 如何使 xargs 使用 -n 附加尾随参数?

linux - 为什么 `xargs head` 打印文件名?

linux - 比较字符串时出现问题 (BASH)