linux变量$ BASH_SUBSHELL与$ SHLVL之间的区别 [英] Difference between linux variables $BASH_SUBSHELL vs $SHLVL
问题描述
我对两者感到困惑.
虽然$ BASH_SUBSHELL内部变量指示子外壳的嵌套级别,但是$ SHLVL变量显示子外壳内没有任何变化.
While the $BASH_SUBSHELL internal variable indicates the nesting level of a subshell, the $SHLVL variable shows no change within a subshell.
这到底是什么意思?如果我在另一个外壳中打开一个外壳,则$ SHLVL的值会增加.那不是子壳吗?
What does it exactly mean? If i open a shell within another shell, the value of $SHLVL increments. Isn't that a subshell?
推荐答案
否,在这种情况下,手动运行新外壳程序(通过/bin/sh
或/bin/bash
等)不是 子外壳程序
No, manually running a new shell (via /bin/sh
or /bin/bash
etc.) is not a subshell in this context.
子外壳程序是指外壳程序自己生成新的外壳程序实例 来处理某些工作的情况.
A subshell is when the shell spawns a new shell instance on its own to handle some work.
使用命令替代(即$(command)
)是一个子shell(较早的backticks调用也是如此).
Using Command Substitution (i.e. $(command)
) is a subshell (as is the older backticks invocation).
使用管道(即echo '5.1+5.3' | bc -l
)创建管道每个组件的子壳.
Using a pipeline (i.e. echo '5.1+5.3' | bc -l
) creates subshells for each component of the pipeline.
使用流程替代(即<(command)
)创建一个子外壳.
Using Process Substitution (i.e. <(command)
) creates a subshell.
分组命令(即(declare a=5; echo $a)
)创建一个子外壳.
Grouping commands (i.e. (declare a=5; echo $a)
) creates a subshell.
在背景(即sleep 1 &
)创建一个子外壳.
Running commands in the background (i.e. sleep 1 &
) creates a subshell.
也许还有其他事情,但这是常见的情况.
There may be other things as well but those are the common cases.
测试起来很简单:
$ 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 )甚至对此进行了一点演示(并且以一种非常不清楚的方式,只是该高级"指南中普遍缺乏严格性和质量的另一例):
The source of your quote (the generally poor, and often better avoided, ABS) even demonstrates this a little bit (and in a rather unclear manner, just another instance of the general lack of rigor and quality in that "Advanced" guide):
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!)
这篇关于linux变量$ BASH_SUBSHELL与$ SHLVL之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!