如何并行运行一系列命令,并将它们的输出存储在变量中?
我试过:
output=`(echo -n "started "; sleep 2; echo "stopped") &`
echo "output before=$output"
wait
echo "output after=$output"
停顿了两秒钟,然后是:
output before=started stopped
output after=started stopped
我预计:
output before=
<2 seconds pause>
output after=started stopped
如何在后台运行一系列命令,并将它们的输出存储在变量中?
最佳答案
来自manual :
If a command is terminated by the control operator
‘&’
, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background. The shell does not wait for the command to finish, and the return status is 0 (true).
解决方法是将输出存储在文件中并从中读取。以下内容可能对您有用:
tempout=$(mktemp)
( echo -n "started "; sleep 2; echo "stopped" ) > "${tempout}" &
echo "output before=$(<$tempout)"
wait
echo "output after=$(<$tempout)"
关于bash:在后台运行多个命令,将输出存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19358930/