如何在 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

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

How to create a local read-only variable in bash?

bashvariableslocalreadonly

提问by bodacydo

How do I create both localand declare -r(read-only) variable in bash?

如何在 bash 中创建localdeclare -r(只读)变量?

If I do:

如果我做:

function x {
    declare -r var=val
}

Then I simply get a global varthat 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 varfrom other functions).

然后我再次获得一个全局(我可以var从其他函数访问)。

How to combine both local and read-only in bash?

如何在bash中结合本地和只读?

回答by mklement0

Even though help localdoesn't mention it in Bash 3.x, localcan 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, declareinside 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 -goption 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 declareshows all options support by bothdeclareand local.

help declare显示所有选项的支持declarelocal