Bash 后台作业
有没有办法允许 bash 中的后台作业修改变量?例如:
[bash]# a=1
[bash]# a=2 &
[1] 14533
[bash]# echo $a
1
我希望 a 的值为 2 而不是 1
Is there a way to allow a background job in bash to modify variables? for ex:
[bash]# a=1
[bash]# a=2 &
[1] 14533
[bash]# echo $a
1
I'd like the value of a to be 2 not 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
变量无法从子进程发送回父进程,因此您尝试做的事情是不可能的。这与
cd
必须是内置 shell 而不是其本身的可执行文件的原因相同。如果它是可执行文件,它将运行、更改目录,然后退出,让您回到目录尚未更改的 shell。Variables can't be sent back to a parent process from a child, so what you're trying to do is impossible. It's the same reason that
cd
has to be a shell builtin rather than an executable in its own right. If it were an executable, it would run, change the directory, and then exit, leaving you back in the shell which hasn't had its directory changed.子进程不能影响其父进程的环境,但如果您的后台进程在评估后结束,您可以“传递”该值作为退出代码。父级可以使用
wait
命令捕获它。下面是后台进程返回加一的变量的示例:A child process can't affect his parent's environment, but if your background process ends after the evaluation you can "pass" the value as an exit code. The parent can catch it with the
wait
command. Here is an example of a background process returning a variable incremented by one:正如卡尔解释得很好,这是不可能的。
示例:
输出将显示值为 1-10 的子级,然后显示旧值为 1 的父级。
As Carl explained quite well, it is impossible.
An example:
Output would show child with value 1-10, and then parent with old value of 1.