test2.sh:
export var1=”hello”;
脚本一
test1-1.sh :
source test2.sh
echo ${var1}
脚本二
test1-2.sh:
sh test2.sh
echo ${var1}
这两个脚本的运行结果分别为:
test1-1.sh:hello
test1-2.sh:
原因是:test1-2.sh中调用sh test2.sh来执行shell是开启一个子shell环境,shell脚本执行完后子shell环境随即关闭,子shell环境的环境变量则销毁,所以执行后,结果并没有反应到父shell里,但是source不同,是在本shell中执行的,所以能够看到结果为hello。
在子环境中的执行shell脚本的方法:./test2.sh、bash test2.sh sh test2.sh
在当前环境中的执行shell脚本的方法:sourcete st2.sh和. test2.sh