函数本地只读与全局只读变量具有相同名称

时间:2011-02-18 07:45:19

标签: bash scope

当我有一个函数本地只读变量和具有相同名称的全局只读变量时,我会感到惊讶。

从全局声明中删除只读选项时。即。

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
$

1 个答案:

答案 0 :(得分:12)

实际上,出于安全原因,明确禁止制作只读全局变量的本地副本,如bash源代码(variables.c:make_local_variable)中所述:

  

针对old_var上下文级别的测试是禁止只读全局变量的本地副本(因为“我”认为这可能是一个安全漏洞)。

(其中“我”不是我,我只是在引用)

/* Since this is called only from the local/declare/typeset code, we can
   call builtin_error here without worry (of course, it will also work
   for anything that sets this_command_name).  Variables with the `noassign'
   attribute may not be made local.  The test against old_var's context
   level is to disallow local copies of readonly global variables (since I
   believe that this could be a security hole).  Readonly copies of calling
   function local variables are OK. */
if (old_var && (noassign_p (old_var) ||
   (readonly_p (old_var) && old_var->context == 0)))
{
  if (readonly_p (old_var))
    sh_readonly (name);
  return ((SHELL_VAR *)NULL);
}