您的位置:首页 > 运维架构 > Shell

关于shell变量的继承总结

2018-08-31 13:18 274 查看

结论:

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

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

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

 

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

[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再进行其他测试,避免变量的值对其他验证有影响。

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: