如何在 bash 中创建本地只读变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34011554/
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
How to create a local read-only variable in bash?
提问by bodacydo
How do I create both local
and declare -r
(read-only) variable in bash?
如何在 bash 中创建local
和declare -r
(只读)变量?
If I do:
如果我做:
function x {
declare -r var=val
}
Then I simply get a global var
that is read-only
然后我只是得到一个var
只读的全局变量
If I do:
如果我做:
function x {
local var=val
}
If I do:
如果我做:
function x {
local var=val
declare -r var
}
Then I get a global again (I can access var
from other functions).
然后我再次获得一个全局(我可以var
从其他函数访问)。
How to combine both local and read-only in bash?
如何在bash中结合本地和只读?
回答by mklement0
Even though help local
doesn't mention it in Bash 3.x, local
can accept the same options as declare
(as of at least Bash 4.3.30, this documentation oversight has been corrected).
即使help local
在 Bash 3.x中没有提到它,local
也可以接受与declare
(至少从 Bash 4.3.30 开始,此文档疏忽已更正)相同的选项。
Thus, you can simply do:
因此,您可以简单地执行以下操作:
local -r var=val
That said, declare
inside a functionby default behaves the same as local
, as @ruakh states in a comment, so your 1st attempt should also have succeeded in creating a localread-only variable.
也就是说,declare
在默认情况下,函数内部的行为与local
@ruakh 在评论中所述的行为相同,因此您的第一次尝试也应该成功地创建了本地只读变量。
In Bash 4.2 and higher, you can overridethis with declare
's -g
option to create a global variable even from inside a function (Bash 3.x does notsupport this.)
在bash 4.2和更高版本,可以覆盖本declare
的-g
选项,甚至从一个函数内部创建一个全局变量(击3.x无法不支持此功能。)
Thanks, Taylor Edmiston:
谢谢,泰勒埃德米斯顿:
help declare
shows all options support by bothdeclare
and local
.
help declare
显示所有选项的支持都declare
和local
。