17

这闻起来很臭,但可能有人可以解释一下:

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

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

1 回答 1

24

管道创建子外壳。bash 手册中说子shell 不能修改其父级的环境。请参阅以下链接:

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

http://wiki.bash-hackers.org/scripting/processtree#actions_that_create_a_subshel​​l

于 2011-07-12T11:28:55.397 回答