變數的有效範圍

變數一旦設定之後,只有該 shell 的環境中有效,它無法影響其它 shell 環境中的變數,因此,一旦 script 檔執行完畢(該 script 執行時為目前 shell 的子 shell),該 script 中的變數即不再有效。

testvar.sh

#! /bin/sh

testvar="Hello World"

echo $testvar

該 script 執行畢,若 echo $testvar,則將為空。

testvar.sh


父 shell 中:
testVAR="Hello World"

testVAR.sh:
#! /bin/sh

echo $testVAR

該 script 執行時(變成子shell),無法取得父 shell 中的變數值。

cd.sh

#! /bin/sh

cd /usr/local
pwd

該 script 執行時,欲切換目錄位置至 /usr/local,唯執行畢,路徑仍不會改變。因為該 script 在子 shell 中執行,當執行完畢時,子 shell 也隨即結束,又回到原父 shell 的環境中,因此路徑不會被改變。

如何達到此一程式構想呢?很簡單,只要讓該 script 在現行 shell 中執行即可:

. cd.sh 或 source cd.sh