天天看點

linux sh source .,linux shell腳本sh和source差別

shell中使用source xxx.sh ,是直接運作xxx.sh的指令,不建立子shell,而sh則建立子shell,子shell裡面 的變量父shell無法使用,對環境變量的修改也不影響父shell。父shell中的局部變量,子shell也無法使用,隻有父shell的環境變量, 子shell能夠使用。

sh 建立了子shell和目前的shell并行執行,子shell中執行,腳本設定的變量不會影響目前shell。一旦子Shell中的執行完畢,此子Shell随即結束,回到父Shell中,不會影響父Shell原本的環境。

linux sh source .,linux shell腳本sh和source差別

sh執行腳本

linux sh source .,linux shell腳本sh和source差別

source執行腳本

還有個辦法可以在父shell和子shell中分别加上 echo $SHLVL ,顯示目前運作層級,可以明顯的看出來:

linux sh source .,linux shell腳本sh和source差別

兩種執行層級不同

[[email protected] home]# cat father.sh

#!/bin/bash

echo "father shell"

echo $SHLVL

echo "father shell"

echo "source son shell"

source son.sh

echo "source son shell"

echo "sh son shell"

sh son.sh

echo "sh son shell"

[[email protected] home]# cat son.sh

#!/bin/bash

echo $SHLVL