4

In Bash, variables declared inside sub-shells are distinct from variables with the same name declared in parent shells, unless the latter are explicitly exported:

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?

swahnee
  • 2,661
  • 2
  • 24
  • 34
  • You can use them as long as you do not change them. But do you want to use them and change the value inside sub-shells? – J. Chomel Mar 18 '16 at 13:46
  • @J.Chomel Yes, I want to use the same name, but with different values. The point is that now, each time I write a new function, and define variables inside it, I'm always at risk of clashing with names already defined upper in the calls stack. The new function I'm writing shouldn't be required to know if some name has already been defined as `readonly` by some parent caller, and when I call a function I shouldn't be checking all the names defined by it and all sub-functions before deciding if I can declare a name as `readonly`. I was hoping that sub-shells allowed me to do that. – swahnee Mar 18 '16 at 14:23

1 Answers1

1

From this post, Use of read-only variables in shell scripts , it looks like the readonly status will not be inherited by child processes.

So you can start a child process, not a sub-shell like so:

readonly a=12
bash -c 'a=13; echo $a'
echo $a

output:

13
12
Dagang
  • 24,586
  • 26
  • 88
  • 133
J. Chomel
  • 8,193
  • 15
  • 41
  • 69