bash:在后台运行多个命令,将输出存储在变量中

标签 bash background-process

如何并行运行一系列命令,并将它们的输出存储在变量中?

我试过:

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/

相关文章:

linux - 如何提取以特定字符开头的标题行(忽略前导空格)?

linux - 尝试迭代存储在变量中的文件

windows - 暂停在 console2 中运行的 bash 中的进程

c++ - mkdir 系统调用创建权限 0755 而不是 0777

python - 从 Python 脚本如何运行其他 Python 脚本?

linux - 如何在 shell 中启 Action 业,即使启动它的 shell 终止,该作业也会持续存在

zsh 提示 - 检查是否有任何后台作业

javascript - 即使选项卡未处于事件状态,如何使 JavaScript 在 Chrome 中以正常速度运行?

php - 在 PHP 文件中在后台运行 FFMPEG

database - MongoDb 2.6 归档问题