【问题标题】:what is difference in `declare -r` and `readonly` in bash?bash中的`declare -r`和`readonly`有什么区别?
【发布时间】:2015-05-21 01:00:39
【问题描述】:

在 bash 中,declare -rreadonly 有什么区别?

$ declare -r a="a1"
$ readonly b="b1"

我不知道该选择哪个。

【问题讨论】:

    标签: bash


    【解决方案1】:

    tl;dr readonly 即使在函数内部也使用 global 的默认范围。 declare 在函数中使用 local 范围(除非 declare -g)。

    乍一看,没有区别。

    使用declare -p检查

    $ declare -r a=a1
    $ readonly b=b1
    $ declare -p a b
    declare -r a="a1"
    declare -r b="b1"
    
    # variable a and variable b are the same
    

    现在查看在函数中定义时的差异

    # define variables inside function A
    $ function A() {
          declare -r x=x1
          readonly y=y1
          declare -p x y
      }
    
    $ A
    declare -r x="x1"
    declare -r y="y1"
    
    # ***calling function A again will incur an error because variable y
    #    was defined using readonly so y is in the global scope***
    
    $ A
    -bash: y: readonly variable
    declare -r x="x1"
    declare -r y="y1"
    
    # after call of function A, the variable y is still defined
    
    $ declare -p x y
    bash: declare: x: not found
    declare -r y="y1"
    


    为了增加更多细微差别,readonly 可用于将本地声明的变量属性更改为只读,而不影响范围。

    $ function A() {
        declare a="a1"
        declare -p a
        readonly a
        declare -p a
    }
    
    $ A
    declare -- a="a1"
    declare -r a="a1"
    
    $ declare -p a
    -bash: declare: a: not found
    
    


    注意:将-g 标志添加到declare 语句(例如declare -rg a="a1")会使变量范围全局。 (感谢@chepner)。

    注意:readonly 是一个“Special Builtin”。如果 Bash 处于 POSIX 模式,则 readonly(而不是 declare)具有 "returning an error status will not cause the shell to exit" 的效果。

    【讨论】:

    • 请注意,从bash 4.2 开始,declare -gr 似乎与readonly 相同。
    • 看起来readonlydeclare -r 之间没有区别。除非指定了-g 标志,否则函数内部的declare 将始终创建局部变量。
    • 我喜欢你自己回答,4 年后回答仍然是最佳答案
    • Re: “readonly 将使变量范围全局”:这是误导;如果一个变量已经是本地的,那么readonly 不会突然使它成为全局变量。说readonly根本不影响变量作用域会更正确,全局作用域是默认作用域。
    • 谢谢@ruakh。好尴尬啊,好久没说出口了。固定。
    猜你喜欢
    • 2017-06-15
    • 2012-05-03
    • 2017-11-08
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    相关资源
    最近更新 更多