0

(Possibly this is the same question as Function local read-only vs. global read-only variable with the same name)

In a script I wrote I'm using readonly key="$1" (for the program parameter) at the global level, and a function uses local key="$1" (for the function parameter this time), too.

To my surprise BASH 4.4 outputs:

...: local: key: readonly variable

In my understanding there is a global readonly variable, but the local variable should be independent of it, even when having the same name, right?

Or did I misunderstand something? Reading the manual page on local did not bring me any further. Or is it that local does not declare a local variable, but a local value for a (global) variable (thus the global read-only status preventing even a local change)?

Would be a rather confusing concept then IMHO.

4
  • 2
    This is by design, variables classified as readonly, can't be redefined in any scope Commented Jan 9, 2023 at 15:00
  • see discussions in bash mail list: this (2011) and this (2019). Commented Jan 9, 2023 at 16:38
  • @Inian However it's different from practically all languages I know. Commented Jan 10, 2023 at 7:26
  • So it seems (as I suspected) that local does not declare or define a (new) local variable, but instead if defines a "local value" for a variable that may exist already. However if such variable exists as read-only, such "local value" is not possible per design. An odd and unexpected concept, but probably the way it is implemented (and generally accepted). Commented Jan 10, 2023 at 7:35

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.