Rak*_*iha 2 bash scripts xargs
我正在远程主机中并行运行一些查询命令,xargs
该命令运行高效且运行良好,但在查找从哪个主机获取查询时遇到一些问题。
现在执行此操作的脚本部分如下所示:
export commands="cmd1; cmd2; "
hosts=("host1" "host2" "host3" "host4")
MaxInstance=10
echo_var(){
echo "Executing in $1:"; sleep 1; echo "Output of: $commands"; return 0;
}
export -f echo_var
printf "%s\n" ${hosts[@]} | xargs -n 2 -P $MaxInstance -I {} $(command -v bash) -c 'echo_var "$1"' _ {}
Run Code Online (Sandbox Code Playgroud)
其输出应如下所示,因为sleep 1
:
Executing in host1:
Executing in host2:
Executing in host3:
Executing in host4:
Output of: cmd1; cmd2;
Output of: cmd1; cmd2;
Output of: cmd1; cmd2;
Output of: cmd1; cmd2;
Run Code Online (Sandbox Code Playgroud)
为了实现与最后显示的输出类似的输出,我必须将现有函数编辑为以下内容,以更接近我想要的结果。但即使在这里,如果我使用printf "%s\n%s" "$name" "$output"
,它有时也会在新行处中断。例如:
echo_var(){
name="Executing in $1:"; sleep 1; output="Output of: $commands";
echo -e "$name: $output" ## will work
# echo -e "$name\n$output" ## will not work or even
# printf "%s\n%s" "$name" "$output" ## will not work
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在不牺牲并行执行速度的情况下,我希望得到如下所示的输出。是否有任何选项可以xargs
指定一次显示整个实例的输出?
Executing in host1:
Output of: cmd1; cmd2;
Executing in host2:
Output of: cmd1; cmd2;
Executing in host3:
Output of: cmd1; cmd2;
Executing in host4:
Output of: cmd1; cmd2;
Run Code Online (Sandbox Code Playgroud)
认识GNU 并行( sudo apt install parallel
):
\n\n\nGNU 并行确保命令的输出与按顺序运行命令时得到的输出相同。
\n
\n 如果您今天使用 xargs 和 tee,您会发现 GNU 并行非常容易使用,\n 因为 GNU 并行被编写为具有与 xargs 相同的选项。
我可以\xe2\x80\x99t 测试它,但你的情况下的命令应该是:
\n\nparallel -n 2 -P $MaxInstance $(command -v bash) -c \'echo_var "$1"\' _ {}\n
Run Code Online (Sandbox Code Playgroud)\n\n请注意,该moreutils
软件包提供了一个parallel
与 GNU parallel 不同的命令。
此示例echo {} start; sleep 1; echo {} ready
针对参数1
、2
和运行3
,首先使用xargs
,然后使用parallel
:
$ echo -e \'1\\n2\\n3\' | xargs -n1 -P3 -I{} bash -c \'echo {} start; sleep 1; echo {} ready\'\n2 start\n1 start\n3 start\n2 ready\n1 ready\n3 ready\n$ parallel \'echo {} start; sleep 1; echo {} ready\' ::: 1 2 3\n1 start\n1 ready\n2 start\n2 ready\n3 start\n3 ready\n
Run Code Online (Sandbox Code Playgroud)\n\n当然,该echo |
方法与 的工作原理相同parallel
,我只是喜欢上面显示的参数列表功能 \xe2\x80\x93 它的作用完全相同。
parallel
如果您因\xe2\x80\x99 未预安装、难以安装/更新或类似原因而犹豫是否使用,我强烈推荐程序作者\xe2\x80\x99s 博客文章《借口不安装》 GNU 并行。