基本用法
source filepath . filepath
功能
它會讓當前 shell 讀入指定檔案,並依序執行裡面的每一行敘述。最典型的用途是:改完初始化檔之後想立刻生效,又不想登出再登入。例如你調整了 /etc/profile,只要執行 source /etc/profile 就能馬上套用。
source 這個名稱來自 C Shell,是 bash 的內建命令;而點命令「.」源自 Bourne Shell,兩者其實是同一件事的不同名字,從寫法上也能看出這段淵源。
當腳本本身具備可執行權限時,sh filepath 與 ./filepath 效果相同。之所以要寫「./」,是因為當前目錄預設不在 PATH 裡,必須用「.」明確指向它。
sh filepath 會另開一個子 shell 去執行腳本。子 shell 繼承父 shell 的環境變數,但它是全新的,裡面產生的變數不會帶回父 shell,除非你用了 export。
而 source filename 只是把腳本裡的敘述逐行在當前 shell 中執行,完全不開子 shell。因此腳本中所有新增或修改的變數,都會留在當前 shell 裡。
建立一個 test.sh,內容只有 A=1,並賦予執行權限:
chmod +x test.sh
sh test.sh 後 echo $A:輸出空白,因為 A=1 沒有回傳給當前 shell。./test.sh:結果一樣。source test.sh 或 . test.sh 後 echo $A:輸出 1,證明變數確實留在當前 shell 中。一句話記法:想要「設定生效在這個 session」,用 source;想要「隔離執行」,用 sh 或 ./。