问题与疑惑
已知
- 命令替换会创建一个子shell(《Linux命令行与Shell脚本大全》时,第11章,11.4.3,最后部分的警告)
- 圆括号命令组,也会创建子shell
又知
- 除非对变量进行export,否则子shell无法继承父shell的变量、或者说父shell定义的变量在子shell中不可见。(根据《Linux命令行与Shell脚本大全》,第6章,6.2.1)
但是
在实践中,命令替换与圆括号命令组,都可以使用当前shell环境当中的变量,如下
#父shell定义的变量,没有export
var1=aaa
# 1、命令替换所在的子shell可以看见父shell中未export的变量
var2=$(echo $var1)
# 2、圆括号命令组的子shell同样可以看见父shell中未export的变量
(
echo $var1
)
问题解决
根据Bash Manual, 3.7.3 Command Execution Environment
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent at invocation. Builtin commands that are invoked as part of a pipeline are also executed in a subshell environment. Changes made to the subshell environment cannot affect the shell’s execution environment.
译
命令替换,放在()中的命令组,以及异步命令,这三种命令会在子shell中环境中创建,该子shell环境是当前shell的一份副本。
参考
https://unix.stackexchange.com/questions/410721/variable-inherited-in-the-subshell-without-exporting-in-the-main-shell
https://www.gnu.org/software/bash/manual/html_node/Command-Execution-Environment.html#Command-Execution-Environment