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

bodacydo picture bodacydo · Dec 1, 2015 · Viewed 7.6k times · Source

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

If I do:

function x {
    declare -r var=val
}

Then I simply get a global var that is read-only

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).

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

Answer

mklement0 picture mklement0 · Dec 1, 2015

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).

Thus, you can simply do:

local -r var=val

That said, declare inside a function by default behaves the same as local, as @ruakh states in a comment, so your 1st attempt should also have succeeded in creating a local read-only variable.

In Bash 4.2 and higher, you can override this with declare's -g option to create a global variable even from inside a function (Bash 3.x does not support this.)


Thanks, Taylor Edmiston:

help declare shows all options support by both declare and local.