bash的管道prevents全局变量赋值 [英] bash piping prevents global variable assignment

查看:225
本文介绍了bash的管道prevents全局变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

unset v
function f {
  v=1
}
f | cat
echo v=$v
f 
echo v=$v

为什么管道(任何命令)prevent第一回波打印1命令?第二回声打印1.我使用的是bash shell。我可以通过复制/粘贴或通过运行这是一个脚本看到这一点。

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.

推荐答案

管道的所有组件(如果有多个)的子shell执行,其变量赋值不会持续到主外壳。

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.

这样做的原因是,bash中不支持实多线程(并发访问变量),其中只有在并行运行的子进程。

The reason for this is that bash does not support real multithreading (with concurrent access to variables), only subprocesses which run in parallel.

如何避免这种

您必须做你想要在主要的bash进程保留(或找到某种方式向其传送)的任何变量赋值。这样做的bash的方法是不使用管道,但在使用过程中,而不是替代:

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:

f > >( cat )

当然,如果您需要在管这两个过程做变量赋值,这将于事无补。然后,你必须想一个更好的机制,而不是(也许协进程和输出某处变量?)

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?)

这篇关于bash的管道prevents全局变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆