gpt4 book ai didi

linux - linux 变量 $BASH_SUBSHELL 与 $SHLVL 之间的区别

转载 作者:IT王子 更新时间:2023-10-29 00:09:49 26 4
gpt4 key购买 nike

我对这两者感到困惑。

While the $BASH_SUBSHELL internal variable indicates the nesting level of a subshell, the $SHLVL variable shows no change within a subshell.

具体是什么意思?如果我在另一个 shell 中打开一个 shell,$SHLVL 的值会增加。那不是子 shell 吗?

最佳答案

不,手动运行一个新的 shell(通过 /bin/sh/bin/bash 等)在这种情况下不是一个子 shell。

子 shell 是指 shell 自己生成一个新的 shell 实例来处理一些工作。

使用 Command Substitution (即 $(command) )是一个子 shell (与旧的反引号调用一样)。

使用 pipeline (即 echo '5.1+5.3' | bc -l )为管道的每个组件创建子 shell 。

使用 Process Substitution (即 <(command) )创建一个子 shell 。

Grouping commands (即 (declare a=5; echo $a) )创建一个子 shell 。

the background 中运行命令(即 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)甚至稍微证明了这一点(并且以一种相当不清楚的方式,只是普遍缺乏严谨性和质量的另一个例子“高级”指南):

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 - linux 变量 $BASH_SUBSHELL 与 $SHLVL 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34799161/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com