BASH:只有当函数通过管道传输时,全局变量才可以在函数中更新(简单示例)
这听起来有问题,但可能有人可以解释它:
以下脚本不起作用,输出如下:
#!/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
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!
#!/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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
管道创建子外壳。 bash 手册中指出,子 shell 无法修改其环境父母。请参阅以下链接:
http://www.gnu.org/software/bash/manual/bashref。 html#Pipelines
http://wiki.bash-hackers.org/scripting/processtree#actions_that_create_a_subshell
A pipe creates a subshell. It's said in the bash manual that subshells cannot modify the environment of their parents. See these links:
http://www.gnu.org/software/bash/manual/bashref.html#Pipelines
http://wiki.bash-hackers.org/scripting/processtree#actions_that_create_a_subshell