繁体   English   中英

从 bash 中的背景子外壳捕获 output?

[英]Capturing output from a background subshell in bash?

我正在尝试在 bash 脚本中运行多个子shell,并将标准输出结果捕获到变量中。 当我在后台运行子shell时,我希望我可以使用等待让子shell完成,然后使用在程序稍后分配结果的变量....但它似乎不起作用。

简单的示例脚本:

l=$(ls) &
wait $!
echo "L=$l"

然后当我运行它时:

$ bash -x test2.sh 
+ wait 16821
++ ls
+ l='test1.sh test2.sh'
+ echo L=
L=

我的测试程序中的 output 会建议变量l应该分配给子shell的结果,但是当我使用 echo 它是空的......

如果我不后台子shell(或使用等待),那么它会按预期工作......

l=$(ls) 
echo "L=$l"

结果是:

$ bash -x test1.sh 
++ ls
+ l='test1.sh test2.sh'
+ echo 'L=test1.sh test2.sh'
L=test1.sh test2.sh

我错过了一些明显的东西还是......?

来自 bash 联机帮助页(强调我的):

Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are re‐set to the values that the shell inherited from its parent at invocation. 作为管道的一部分调用的内置命令也在子 shell 环境中执行。 对子 shell 环境所做的更改不会影响 shell 的执行环境

因此,如果没有背景, l=$(ls) &会像(l=$(ls))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM