[英]Variable scope with child functions
我今天读了
“局部只能在一个函数内使用;它使变量名具有一个限于该函数及其子级的可见范围。” ABS指南作者认为此行为是错误。
我想出了这个脚本
begin () {
local foo
alpha
}
alpha () {
foo=333 bar=444
bravo
}
bravo () {
printf 'foo %3s bar %s\n' "$foo" "$bar"
}
begin
bravo
输出量
foo 333 bar 444
foo bar 444
如您所见,因为我没有local bar
,所以它泄漏到了全局范围内。 问题:
set -a
所有内容标记为要导出的方法吗? 子函数可以使用的局部变量实际上是一个错误,还是仅仅是他的意见?
不,这不是错误。 那只是他的意见。
Bash是否有一种将所有内容标记为本地的方法,类似于set -a将所有内容标记为要导出的方法吗?
没有。
失败了,Bash有没有办法检查这些泄漏的全局变量?
是。 只需尝试“设置”或“声明”,两者都没有任何参数。
失败了,Bash有没有办法检查这些泄漏的全局变量?
否。Bash有一个未公开的概念,称为“隐藏变量”,它使得无法在不干扰变量的情况下测试是否设置了局部变量。
此测试演示了隐藏变量以及未设置内置变量的范围敏感性质。
function f {
case $1 in 1)
typeset x=1
f 2
;;
2)
typeset x
unset -v x # Does nothing (demonstrates hidden local)
f 3
;;
[345])
printf "x is %sunset\n" ${x+"not "}
unset -v x
f $(($1 + 1))
esac
}
f 1
# output:
# x is unset
# x is not unset
# x is unset
Bash有一种方法可以使用declare -g
强制设置全局,但是没有办法强制bash取消引用它或测试是否设置了bash,从而使该功能的实用性非常有限。
希望这可以清楚地说明问题
f() {
local x="in x" # Assign a local
declare -g x=global # Assign a global
declare -p x # prints "in x"
unset -v x # try unsetting the local
declare -p x # error (x is invisible)
}
f
declare -p x # x is visible again, but there's no way to test for that before now.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.