在以下脚本中,函数 (g) 的局部变量 (i) 的值被它调用的函数 (f) 覆盖。
#!/usr/bin/env bash
f() {
#local i # Let's assume whoever wrote this function f forgot,
# to declare its variables as being local to it
i=0
}
g() {
local i # How to declare i as being only modifiable in the
# scope of g, but not by functions g calls?
for i in 1 2 3; do
f # overwrites the value of i with 0
echo "i: $i"
done
}
g
# output:
# i: 0
# i: 0
# i: 0
有没有办法将 bash 变量的暴露限制在它们声明的范围内?
如果有人没有明确地将它们声明为全局变量(例如使用 declare -g),是否有办法使变量默认为函数局部?