結論:
默認,父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定義的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

[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運行結束后,其定義的全局變量和普通變量均自動銷毀。
注意:測試過程中如果使用了source運行腳本,請退出終端或unset再進行其他測試,避免變量的值對其他驗證有影響。