【问题标题】:Function local read-only vs. global read-only variable with the same name函数本地只读与同名全局只读变量
【发布时间】: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
$

【问题讨论】:

标签: bash scope


【解决方案1】:

实际上,出于安全原因,明确禁止制作只读全局变量的本地副本,如 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);
}

【讨论】:

  • 不是我要查找文档的第一个地方。
猜你喜欢
  • 2015-01-17
  • 2010-11-27
  • 2019-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 1970-01-01
  • 2015-08-29
相关资源
最近更新 更多