1
#!/bin/bash

readonly x=2

function test {
 local x=1
 echo ${x}
}

test
echo $x

The result is,

readonly-local-test.sh: line 6: local: x: readonly variable
2
2

When the variable is read-only this happens. However, if I remove the readonly restriction as below,

#!/bin/bash

x=2
function test {
 local x=1
 echo ${x}
}

test
echo $x

The result is,

1
2

Why read only global variables can't be shadowed?

  • 1
    You just can't redefine the readonly variables – Inian Mar 13 at 4:15
  • Oh ok.. then that's just a design decision I guess – Snitch Mar 13 at 4:22
0

AFAIK this behavior can be named "Work as design". You have readonly variable and the idea is you can't change the value of this variable. In bash you do not have the option to define variable which overwrite the set of such global variables.

  • I do realize that readonly variables shouldn't be allowed to change. My question was about, a normal global variable can be shadowed by a local variable, whereas a readonly global variable cannot be shadowed. – Snitch Mar 19 at 2:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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