I am reading a Linux shell scripting book and have found the following warning:
"Command substitution creates what's called a subshell to run the
enclosed command. A subshell is separate child shell generated from
the shell that's running the script. Because of that, any variables
you create in the script aren't available to the subshell command".
I have tried to create a variable in my current bash shell's CLI and then enter the subshell to check whether I can print it on the screen. So yes, I can't do it, seems to be according the citation above. However, I have run the following script with command substitution:
#!/bin/bash
var=5.5555
ans=$(echo $var)
echo $ans
And the result is:
5.5555
As I understood, it shouldn't print the value of var since the subshell shouldn't be able to "see it". Why does it happen?
Best Answer
The statement:
is false. The scope of a variable defined in the parent shell is the entire script (including subshells created with command substitution).
Running:
will give the result:
$var
is resolved by the subshell:See also the example 21-2.