source (別名 .) 是 Bash 內建指令,能在當前 Shell 進程中讀取並執行腳本,使腳本內的變數、函式、別名等直接影響當前環境。這與 ./script.sh 啟動子 Shell 執行有本質差異。本文透過實測對比,徹底釐清用法與應用場景。
source filename
. filename # 點號空格檔名,Bourne Shell 相容寫法
# 兩者完全等效
| 維度 | source script.sh | ./script.sh |
|---|---|---|
| 執行進程 | 當前 Shell (PID 不變) | fork 子 Shell (新 PID) |
| 環境變數 | 保留於當前 Shell | 子 Shell 結束隨即銷毀 |
| cd/pushd/目錄切換 | 影響當前 Shell 工作目錄 | 僅影響子 Shell |
| 函式/別名定義 | 可直接在當前 Shell 使用 | 子 Shell 結束失效 |
| 執行權限 | 不需 +x | 需 chmod +x |
| Shebang | 忽略 (由當前 Shell 解釋) | 依 shebang 指定解釋器 |
# 1. 建立測試腳本
cat > test.sh <<'EOF'
#!/bin/bash
export KKK=111
echo "腳本內 KKK=$KKK"
EOF
# 2. 用 source 執行
source test.sh
echo $KKK # 輸出 111 ✅
# 3. 新開終端機 (新 Shell) 執行 ./test.sh
./test.sh
echo $KKK # 無輸出 ❌ (子 Shell 變數未傳回父 Shell)
~/.bashrc、~/.bash_profile、/etc/profile 後,source ~/.bashrc 即時生效,無需重新登入。source build_steps.sh 依序執行,&& 確保前一步成功才執行下一步。source /usr/share/bash-completion/bash_completion 載入補全函式。source venv/bin/activate 修改當前 Shell 的 PATH、PS1。# 檔案:make_command
make mrproper && \
make menuconfig && \
make -j$(nproc) && \
make modules_install && \
make install && \
echo "編譯完成,請更新 bootloader"
# 執行:source make_command
exit 會直接結束當前 Shell (登出),慎用。建議用 return (函式) 或條件判斷控制流程。export 配合 env -i 隔離,避免汙染互動 Shell。source 非 POSIX 標準,移植性要求高的腳本請用 .。掌握 source「在當前 Shell 執行」的特性,能靈活管理環境變數、模組化腳本、自動化建置流程,是 Shell 進階使用者的必備技能。