BASH:只有当该函数通过管道传输时,全局变量才能在函数中更新(简单示例)

时间:2011-07-12 10:41:18

标签: linux bash variables cat

这闻起来很麻烦,但可能有人可以解释它:

以下脚本不起作用,输出如下:

#!/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"

输出:

func before set> OLD
func after set> NEW
final value> OLD

现在,只需取消| 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"

输出:

func before set> OLD
func after set> NEW
final value> NEW

1 个答案:

答案 0 :(得分:24)

管道创建子壳。它在bash manual中说,子壳不能改变他们父母的环境。请参阅以下链接:

http://www.gnu.org/software/bash/manual/bashref.html#Pipelines

http://wiki.bash-hackers.org/scripting/processtree#actions_that_create_a_subshell