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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:04:10  来源:igfitidea点击:

BASH: Global variables aren't updateable in a function only when that function is piped (simple example)

linuxbashvariablescat

提问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 | catand 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_subshel​​l