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.

U. Windl
  • 3,480
  • 26
  • 54
  • 2
    This is by design, variables classified as `readonly`, can't be redefined in _any_ scope – Inian Jan 09 '23 at 15:00
  • see discussions in bash mail list: [this](https://lists.gnu.org/archive/html/bug-bash/2011-02/msg00105.html) (2011) and [this](https://lists.gnu.org/archive/html/bug-bash/2019-03/msg00150.html) (2019). – pynexj Jan 09 '23 at 16:38
  • @Inian However it's different from practically all languages I know. – U. Windl Jan 10 '23 at 07: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). – U. Windl Jan 10 '23 at 07:35

0 Answers0