【发布时间】:2011-03-07 13:31:22
【问题描述】:
当我有一个同名的函数本地只读变量和全局只读变量时,我得到了一个令人惊讶的行为。
从全局声明中删除只读选项时。即
declare -r var="main"
改为:
declare var="main"
我得到了预期的行为。我一直在阅读 bash 手册页,但找不到对这种行为的解释。能否请您指出手册中解释问题的部分?
我认为这是与How does lexical scoping supported in different shell languages? 类似但更具体的问题。
详情:
$ cat readonly_variable.sh
#!/bin/bash
# expected output:
#
# BASH_VERSION = 3.2.25(1)-release
# function
# main
#
# but instead getting:
#
# BASH_VERSION = 3.2.25(1)-release
# ./readonly_variable.sh: line 6: local: var: readonly variable
# main
# main
#
# when read-only option (-r) is removed from global declaration (*), the output
# is expected
set -o nounset
function func {
local -r var="function"
echo "$var"
}
declare -r var="main" # (*)
echo BASH_VERSION = $BASH_VERSION
echo $(func)
echo $var
exit 0
我坚持使用这个特定的 Bash 版本。
$ ./readonly_variable.sh
BASH_VERSION = 3.2.25(1)-release
./readonly_variable.sh: line 24: local: var: readonly variable
main
main
$
【问题讨论】:
-
在 gnu.bash.bug 邮件列表中有这个问题的 recent discussion。