在艰难地学习 bash 时,我发现它subshells
从父级继承变量,并且可以在自己的范围内覆盖它。除非我们使用,否则它不会反映到父 shell 中export
,
我尝试了下面的示例来导出 VAR1 ,但我没有将 VAR1 值反映到我的父 shell 中。有人可以解释一下如果我在这里遗漏了什么,在此先感谢。
anupam:~$ VAR1="variable under shell $$.pid and $BASHPID.bashid"
anupam:~$ set -o posix; set | grep -i VAR1
VAR1='variable under shell 6137.pid and 6137.bashid'
anupam:~$ (
> echo Inside the subshell
> echo ${VAR1}
> VAR1="variable under subshell with $$.pid and $BASHPID.bashid"
> echo ${VAR1}
> )
Inside the subshell
variable under shell 6137.pid and 6137.bashid
variable under subshell with 6137.pid and 6193.bashid
anupam:~$ set -o posix; set | grep -i VAR1
VAR1='variable under shell 6137.pid and 6137.bashid'
anupam:~$ (
> echo Inside another subshell
> echo ${VAR1}
> VAR1="variable under another subshell with $$.pid and $BASHPID.bashid"
> echo ${VAR1}
> export VAR1="exported variable under another subshell with $$.pid and $BASHPID.bashid"
> )
Inside another subshell
variable under shell 6137.pid and 6137.bashid
variable under another subshell with 6137.pid and 6208.bashid
anupam:~$ set -o posix; set | grep -i VAR1
VAR1='variable under shell 6137.pid and 6137.bashid'
anupam:~$
孩子无法改变父母的环境。您可以将变量从父级导出到子级,反之亦然。