In Bash, variables declared inside sub-shells are distinct from variables with the same name declared in parent shells, unless the latter are explicitly export
ed:
a=12
(a=13; echo $a)
echo $a
# Output:
# 13
# 12 Outer variable wasn't changed
However, if the outer variable is declared as readonly
, the sub-shell cannot redefine it, preventing from reusing the same name, even if it wasn't going to do any harm:
readonly a=12
(a=13; echo $a)
echo $a
# Output:
# test.sh: line 2: a: readonly variable
# 12 Only the outer echo is executed
If I declare as readonly
also the variable inside the sub-shell, I still get the same error, but this time the echo
inside the sub-shell is executed as well:
readonly a=12
(readonly a=13; echo $a)
echo $a
# Output:
# test.sh: line 2: a: readonly variable
# 12 global value is used in sub-shell
# 12
Now, as far as my goal is concerned, which is avoiding variables defined in child functions (functions called by other functions) to conflict with variables defined in parent functions with the same name, I could be content with using non-readonly
variables inside parent shells. However, it's really useful to declare variables as readonly
if they're not intended to be changed, since it helps preventing several kinds of bugs, so I'd like to avoid giving up on them.
So, do you know if there's a way to reuse variable names declared as readonly
in parent shells, from within subshells?