Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux source 指令詳解:在當前 Shell 執行腳本與環境變數傳遞

編輯:Linux 教學

source (或簡寫 .) 是 Bash 內建指令,用於在當前 Shell 進程中讀取並執行指定腳本檔案。不同於 ./script.sh 開啟子 Shell,source 能保留腳本中設定的環境變數、函數、別名等於當前會話,常用於重新載入設定檔 (如 .bashrc) 或模組化腳本管理。

基本語法與等效形式

source filename
. filename          # 同義,源自 Bourne Shell
  • 檔案不需執行權限 (不需 chmod +x)
  • 路徑可為相對或絕對,若無路徑會搜尋 $PATH

核心差異:source vs 子 Shell 執行

實戰範例

1. 重新載入 .bashrc 讓修改即時生效

# 編輯 ~/.bashrc 新增 export EDITOR=vim
source ~/.bashrc
echo $EDITOR   # 輸出 vim,無需重新登入

2. 腳本傳遞變數給當前 Shell

# test.sh
export KKK=111

# 執行
source test.sh
echo $KKK   # 111

# 若用 ./test.sh 則 $KKK 為空

3. 編譯核心自動化腳本 (source 妙用)

建立 make_command 檔案:

make mrproper &&
make menuconfig &&
make dep &&
make clean &&
make bzImage &&
make modules &&
make modules_install &&
cp arch/i386/boot/bzImage /boot/vmlinuz_new &&
cp System.map /boot &&
vi /etc/lilo.conf &&
lilo -v

每次編譯只需在核心源碼目錄下:

source make_command

優點:&& 確保前一指令成功才執行下一條,避免錯誤繼續;變數、函數定義留在當前 Shell,方便除錯。

注意事項

  • source 執行的腳本若含 exit,會直接登出當前 Shell!請用 return 結束腳本。
  • 大量指令建議寫成函數或獨立腳本配合 source,保持互動環境整潔。
  • 若腳本需參數,source script.sh arg1 arg2 內部可用 $1, $2 存取。

測試驗證

# 建立 test.sh
#!/bin/bash
export s=/home/jboss/

# 當前 Shell 執行
source test.sh
echo $s   # /home/jboss/

# 新開終端機 (新 Shell) 執行
./test.sh
echo $s   # 空值,因子 Shell 結束變數隨之消失
Copyright © Windows教程網 All Rights Reserved
方式進程環境變數影響適用場景
source script.sh / . script.sh當前 Shell (PID 不變)腳本中 export VAR=val 會保留在當前 Shell載入設定檔、定義函數/別名、模組化腳本
./script.sh / bash script.sh新子 Shell (PID 改變)子 Shell 結束後變數消失,不影響父 Shell獨立執行的程式、不想汙染當前環境