不,手动运行一个新的 shell(通过/bin/sh
or /bin/bash
等)是not在此上下文中的子 shell。
子 shell 是指 shell 生成新的 shell 实例时在其自己的来处理一些工作。
Using 命令替换 http://www.gnu.org/software/bash/manual/bashref.html#Command-Substitution (i.e. $(command)
) 是一个子 shell(与旧的反引号调用一样)。
Using a pipeline http://www.gnu.org/software/bash/manual/bashref.html#Pipelines (i.e. echo '5.1+5.3' | bc -l
) 为管道的每个组件创建子 shell。
Using 流程替代 http://www.gnu.org/software/bash/manual/bashref.html#Process-Substitution (i.e. <(command)
) 创建一个子shell。
分组命令 http://www.gnu.org/software/bash/manual/bashref.html#Command-Grouping (i.e. (declare a=5; echo $a)
) 创建一个子shell。
运行命令在的背景 http://www.gnu.org/software/bash/manual/bashref.html#Lists (i.e. sleep 1 &
) 创建一个子shell。
可能还有其他情况,但这些都是常见情况。
测试这个很容易:
$ printf "Outside: $BASH_SUBSHELL , $SHLVL\nInside: $(echo $BASH_SUBSHELL , $SHLVL)\n"
Outside: 0 , 1
Inside: 1 , 1
$ (printf "Outside: $BASH_SUBSHELL , $SHLVL\nInside: $(echo $BASH_SUBSHELL , $SHLVL)\n")
Outside: 1 , 1
Inside: 2 , 1
$ bash -c 'printf "Outside: $BASH_SUBSHELL , $SHLVL\nInside: $(echo $BASH_SUBSHELL , $SHLVL)\n"'
Outside: 0 , 2
Inside: 1 , 2
$ bash -c '(printf "Outside: $BASH_SUBSHELL , $SHLVL\nInside: $(echo $BASH_SUBSHELL , $SHLVL)\n")'
Outside: 1 , 2
Inside: 2 , 2
您引用的来源(通常是穷人,并且通常最好避免,ABS http://www.tldp.org/LDP/abs/html/subshells.html)甚至稍微演示了这一点(并且以一种相当不清楚的方式,只是“高级”指南中普遍缺乏严谨性和质量的另一个例子):
echo " \$BASH_SUBSHELL outside subshell = $BASH_SUBSHELL" # 0
( echo " \$BASH_SUBSHELL inside subshell = $BASH_SUBSHELL" ) # 1
( ( echo " \$BASH_SUBSHELL inside nested subshell = $BASH_SUBSHELL" ) ) # 2
# ^ ^ *** nested *** ^ ^
echo
echo " \$SHLVL outside subshell = $SHLVL" # 3
( echo " \$SHLVL inside subshell = $SHLVL" ) # 3 (No change!)