I get a suprising behaviour when I have a function local read-only variable and global read-only variable with the same name.
When read-only option is removed from global declaration. I.e.
declare -r var="main"
is changed to:
declare var="main"
I get the expected behaviour. I've been reading bash man page but I can't find an explanation to this behaviour. Could you please point me to the section(s) of the manual explaining the issue ?
I think this is a similar kind of issue than How does lexical scoping supported in different shell languages? but more specific.
Details:
$ cat readonly_variable.sh
#!/bin/bash
# expected output:
#
# BASH_VERSION = 3.2.25(1)-release
# function
# main
#
# but instead getting:
#
# BASH_VERSION = 3.2.25(1)-release
# ./readonly_variable.sh: line 6: local: var: readonly variable
# main
# main
#
# when read-only option (-r) is removed from global declaration (*), the output
# is expected
set -o nounset
function func {
local -r var="function"
echo "$var"
}
declare -r var="main" # (*)
echo BASH_VERSION = $BASH_VERSION
echo $(func)
echo $var
exit 0
I'm stucked to this particular Bash version.
$ ./readonly_variable.sh
BASH_VERSION = 3.2.25(1)-release
./readonly_variable.sh: line 24: local: var: readonly variable
main
main
$