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 filename
. filename          # 點號空格檔名,Bourne Shell 相容寫法
# 兩者完全等效

核心差異:source vs ./script.sh

維度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)

常見應用場景

  1. 重新載入環境設定:修改 ~/.bashrc、~/.bash_profile、/etc/profile 後,source ~/.bashrc 即時生效,無需重新登入。
  2. 編譯核心/專案自動化:將長指令串聯成檔案,source build_steps.sh 依序執行,&& 確保前一步成功才執行下一步。
  3. 載入函式庫:source /usr/share/bash-completion/bash_completion 載入補全函式。
  4. 虛擬環境激活: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 進階使用者的必備技能。

Copyright © Windows教程網 All Rights Reserved