Linux BASH:只有当函数被管道传输时,全局变量才能在函数中更新(简单示例)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6662915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BASH: Global variables aren't updateable in a function only when that function is piped (simple example)
提问by David Parks
This smells buggy, but probably, someone can explain it:
这闻起来有问题,但可能有人可以解释一下:
The following script doesn't work, the output is below:
以下脚本不起作用,输出如下:
#!/bin/bash
GLOBAL_VAR="OLD"
myfunc() {
echo "func before set> $GLOBAL_VAR"
GLOBAL_VAR="NEW"
echo "func after set> $GLOBAL_VAR"
}
myfunc | cat
echo "final value> $GLOBAL_VAR"
Output:
输出:
func before set> OLD
func after set> NEW
final value> OLD
Now, just take off the | cat
and it works!
现在,只需取下| cat
它就可以了!
#!/bin/bash
GLOBAL_VAR="OLD"
myfunc() {
echo "func before set> $GLOBAL_VAR"
GLOBAL_VAR="NEW"
echo "func after set> $GLOBAL_VAR"
}
myfunc
echo "final value> $GLOBAL_VAR"
Output:
输出:
func before set> OLD
func after set> NEW
final value> NEW
采纳答案by Rajish
A pipe creates a subshell. It's said in the bash manualthat subshells cannot modify the environment of their parents. See these links:
管道创建子壳。它在说bash的手册是子shell不能修改其父母的环境。请参阅这些链接:
http://www.gnu.org/software/bash/manual/bashref.html#Pipelines
http://www.gnu.org/software/bash/manual/bashref.html#Pipelines
http://wiki.bash-hackers.org/scripting/processtree#actions_that_create_a_subshell
http://wiki.bash-hackers.org/scripting/processtree#actions_that_create_a_subshell