Bash Variable Visibility in Subshell of Command Substitution

bashshell

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:

Because of that, any variables you create in the script aren't available to the subshell command.

is false. The scope of a variable defined in the parent shell is the entire script (including subshells created with command substitution).

Running:

#!/bin/bash
var=5.5555
ans1=$(echo $var)
ans2=$(var=6; echo $var)
echo $ans1
echo $ans2

will give the result:

5.5555
6

$var is resolved by the subshell:

  • if no local variable is specified, the value of three global variable is used
  • if a local variable is specified, it uses its value

See also the example 21-2.

Related Question