bash 管道阻止全局变量赋值
unset v
function f {
v=1
}
f | cat
echo v=$v
f
echo v=$v
为什么管道(到任何命令)会阻止第一个 echo 命令打印 1?第二个 echo 打印 1。我使用的是 bash shell。我可以通过复制/粘贴或将其作为脚本运行来查看。
unset v
function f {
v=1
}
f | cat
echo v=$v
f
echo v=$v
Why does piping (to any command) prevent the first echo command from printing 1? The second echo prints 1. I'm using a bash shell. I can see this by copy/paste or by running this as a script.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
管道的所有组件(如果多个)都在子 shell 中执行,并且它们的变量分配不会保留到主 shell。
原因是 bash 不支持真正的多线程(并发访问变量),只支持并行运行的子进程。
如何避免这种情况:
您必须在 main bash 进程中保留想要保留的任何变量赋值(或者找到某种方法将它们转移到那里)。 bash 的方法是不使用管道,而是使用进程替换:
当然,如果您需要在管道的两个进程中进行变量赋值,这将无济于事。然后你必须考虑一个更好的机制(也许协处理,并在某个地方输出变量?)
All components of a pipeline (if more than one) are executed in a subshell, and their variable assignments do not persist to the main shell.
The reason for this is that bash does not support real multithreading (with concurrent access to variables), only subprocesses which run in parallel.
How to avoid this:
You have to do any variable assignments you want to retain in the main bash process (or find some way to transfer them there). The bash way of doing this would be not to use a pipe, but use process substitution instead:
Of course, this will not help if you need to do variable assignments in both processes of a pipe. Then you have to think of a better mechanism instead (maybe coprocesses, and output the variables somewhere?)