22

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?

bodacydo
  • 75,521
  • 93
  • 229
  • 319
  • 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 Dec 01 '15 at 02:29

1 Answers1

37

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775