I am learning shell scripts and stuck at this little experimental shell scripts:
#!/usr/bin/env bash A=1 (A=2;echo "A is $A in $SHLVL") echo "A is $A in $SHLVL" exit 0
Without doubt, $A
in line 3 and line 4 are different from each other, which can be explained that it is because the parent process cannot read variables created in the child process, that is, the subshell. However, the $SHLVL
in line 3 and line 4 are the SAME, which I thought that $A
in line 3 should have been bigger than $A
in line 4 by 1. Didn’t commands in line 3 executed in subshell? I don’t know where I misinterpreted.
Advertisement
Answer
You actually need to use $BASH_SUBSHELL
instead of $SHLVL
here.
$BASH_SUBSHELL
is an internal variable that indicates the nesting level of a subshell.
Change your script to this:
#!/usr/bin/env bash A=1 (A=2;echo "A is $A in $BASH_SUBSHELL:$SHLVL") echo "A is $A in $BASH_SUBSHELL:$SHLVL"
Now it will output:
A is 2 in 1:2 A is 1 in 0:2
You can see $BASH_SUBSHELL
changes with the nesting level but $SHLVL
remains same.