shell 变量没有从子 shell 导出?

shell 变量没有从子 shell 导出?

在艰难地学习 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:~$ 

答案1

子进程无法改变父进程的环境。你可以将变量从父进程导出到子进程,但反之则不行。

相关内容