24

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?

1
  • 6
    declare is documented as declaring a local variable, unless you explicitly request a global one by setting the -g flag. I've just tested on my own system, and it behaves as documented. Can you clarify why you believe this is not the case?
    – ruakh
    Commented Dec 1, 2015 at 2:29

1 Answer 1

39

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.