我试图获得异步运行的多个命令的结果,到目前为止我得到了:
#!/usr/bin/env bash
sum=0
for i in `seq 1 10`;
do
sum+=$(calculationCommand) &
done
wait
echo $sum
但它每次输出0,有人可以帮我找到错误并纠正它,谢谢!
答案 0 :(得分:1)
这是ShellCheck:
Line 6:
sum+=$(calculationCommand) &
^-- SC2030: Modification of sum is local (to subshell caused by backgrounding &).
Line 10:
echo $sum
^-- SC2031: sum was modified in a subshell. That change might be lost.
您无法更新其他进程的变量。相反,将结果写入文件wait
以使其完成,然后从文件中读取数据。
以下是一个例子:
#!/bin/bash
calculationCommand() {
sleep 5
echo 2
}
for i in {1..10}
do
calculationCommand > tmp.$i &
done
wait
sum=0
for number in $(cat tmp.{1..10})
do
(( sum += number ))
done
echo "$sum"
替代方案包括使用fifo而不是10个文件。