关于shell变量的继承总结

结论:

默认,父shell和子shell的变量是隔离的。

sh方式运行脚本,会重新开启一个子shell,无法继承父进程的普通变量,能继承父进程export的全局变量。

source或者. 方式运行脚本,会在当前shell下运行脚本,相当于把脚本内容加载到当前shell后执行,自然能使用前面定义的变量。

验证:在子shell中调用父shell普通变量

[root@gjt scripts]# echo $b

[root@gjt scripts]# echo $a

[root@gjt scripts]# b=gaga
[root@gjt scripts]# echo $b
gaga
[root@gjt scripts]# cat test1.sh 
a=haha
echo "test1: $a"
echo "test1: $b"
sh /root/scripts/test2.sh
[root@gjt scripts]# cat test2.sh 
echo "test2:$a"
echo "test2:$b"
[root@gjt scripts]# sh test1.sh 
test1: haha
test1:
test2:
test2:
#执行过程解释:
sh test1.sh    ==>重新启动一个子shell
a=haha         ==>a变量赋值
echo "test1: $a"    ==>输出:test1: haha
echo "test1: $b"    ==>输出:test1: 因为子shell不会继承父shell的普通变量,所以$b为空
sh /root/scripts/test2.sh    ==>重新启动一个子shell
echo "test2:$a"    ==>输出:test2: 同上,$a为空
echo "test2:$b"    ==>输出:test2: 同上,$b为空

[root@gjt scripts]# source test1.sh 
test1: haha
test1: gaga
test2:
test2:
[root@gjt scripts]# echo $a
haha
#执行过程解释:
source test1.sh    ==>在当前shell下执行脚本
a=haha         ==>a变量赋值
echo "test1: $a"    ==>输出:test1: haha
echo "test1: $b"    ==>输出:test1: gaga 在运行脚本之前在终端定义了b变量。
sh /root/scripts/test2.sh  ==>重新启动一个子shell
echo "test2:$a"    ==>输出:test2: $a未定义
echo "test2:$b"    ==>输出:test2: $b未定义

[root@gjt scripts]# echo $a    ==>输出:haha,source test1.sh时定义了。
验证:在子shell中调用父shell普通变量

验证:在子shell中调用父shell定义的export全局变量

[root@gjt scripts]# echo $b

[root@gjt scripts]# echo $a

[root@gjt scripts]# cat test1.sh 
export a=haha
echo "test1: $a"
echo "test1: $b"
sh /root/scripts/test2.sh
[root@gjt scripts]# cat test2.sh 
echo "test2:$a"
echo "test2:$b"
[root@gjt scripts]# export b=gaga
[root@gjt scripts]# sh test1.sh 
test1: haha
test1: gaga
test2:haha
test2:gaga

#输出说明,父shell定义的全局变量可以传递给子shell以及子shell的子shell
验证:在子shell中调用父shell定义的export全局变量
[root@gjt scripts]# echo $b

[root@gjt scripts]# echo $a

[root@gjt scripts]# cat test1.sh 
export a=haha
echo "test1: $a"
echo "test1: $b"
sh /root/scripts/test2.sh
[root@gjt scripts]# cat test2.sh 
echo "test2:$a"
echo "test2:$b"
[root@gjt scripts]# export b=gaga
[root@gjt scripts]# sh test1.sh 
test1: haha
test1: gaga
test2:haha
test2:gaga
[root@gjt scripts]# echo $a

[root@gjt scripts]# 

#最后的$a输出为空,说明子shell运行结束后,其定义的全局变量和普通变量均自动销毁。
验证:在父shell中无法调用子shell定义的export全局变量

注意:测试过程中如果使用了source运行脚本,请退出终端或unset再进行其他测试,避免变量的值对其他验证有影响。

原文地址:https://www.cnblogs.com/guojintao/p/9565282.html