bash bash中的`declare -r`和`readonly`有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30362831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:01:02  来源:igfitidea点击:

what is difference in `declare -r` and `readonly` in bash?

bash

提问by JamesThomasMoon1979

In bash, what is the difference in declare -rand readonly?

在bash,就是在差异declare -rreadonly

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

I'm not sure which to choose.

我不确定该选择哪个。

回答by JamesThomasMoon1979

tl;drreadonlyuses the default scope of globaleven inside functions. declareuses scope localwhen in a function (unless declare -g).

tl;dr甚至在函数内部readonly使用global的默认范围。 在函数中declare使用局部作用域(除非declare -g)。

At first glance, no difference.

乍一看,没什么区别。

Examining using declare -p

使用声明 -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

Now review the difference when defined within a function

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

# 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"



To add more nuance, readonlymay be used to change a locally declared variable property to readonly, not affecting scope.

要添加更多细微差别,readonly可用于将本地声明的变量属性更改为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





Note: adding -gflag to the declarestatement (e.g. declare -rg a="a1") makes the variable scope global. (thanks @chepner).

注意:-gdeclare语句中添加标志(例如declare -rg a="a1")会使变量作用域成为global。(感谢@chepner)。

Note: readonlyis a "Special Builtin". If Bash is in POSIXmode then readonly(and not declare) has the effect "returning an error status will not cause the shell to exit".

注意:readonly是“特殊内置”。如果 Bash 处于POSIX模式,则readonly(而不是declare)具有返回错误状态不会导致外壳退出”的效果