source (別名 .) 是 Bash 內建指令,用於在當前 Shell 進程中讀取並執行腳本檔案,使變數、函數、別名等定義即時生效於當前環境。這與執行腳本 (./script.sh) 建立子 Shell 截然不同。本文詳細說明語法、運作原理、典型應用場景與常見誤區。
語法與別名
source filename
# 等同於
. filename
source 來自 C Shell (csh/tcsh) 傳統。
. (dot command) 來自 Bourne Shell (sh) 傳統,POSIX 標準。
核心特性對比
| 特性 | source / . | 執行腳本 (./script.sh) |
| 執行環境 | 當前 Shell 進程 | 子 Shell 進程 |
| 環境變數/函數/別名 | 保留於當前 Shell | 子 Shell 結束即銷毀 |
| 檔案權限要求 | 無需執行權限 (只需讀取權限) | 需執行權限 (+x) |
| Shebang (#!/bin/bash) | 被忽略 | 決定解譯器 |
典型應用場景
- 重新載入環境設定檔:修改
~/.bashrc、~/.bash_profile、/etc/profile 後:
source ~/.bashrc
# 或
. /etc/profile
- 載入專案環境變數:Android 編譯、虛擬環境啟動:
source build/envsetup.sh
source venv/bin/activate
- 模組化腳本設計:將共用函數/變數置於
common.sh,在主腳本 source common.sh 復用。
source vs export 影響範圍
source:影響父 Shell (當前 Shell)及後續衍生的子 Shell。
export:僅影響當前 Shell 及其子 Shell,無法回傳給父 Shell。
常見誤區與最佳實踐
❌ 錯誤:sh /etc/profile → 在子 Shell 執行,環境變數不會回傳。
✅ 正確:source /etc/profile 或 . /etc/profile → 當前 Shell 執行,變數即時生效。
進階:source 回傳值與錯誤處理
- 腳本中
return N 可回傳狀態碼 (0 成功,非 0 失敗),source 會捕獲該回傳值存入 $?。
- 腳本語法錯誤會導致
source 失敗並輸出錯誤訊息,但不會終結當前 Shell (除非設定 set -e)。

總結:source 是 Shell 環境配置管理的核心指令,理解其「當前進程執行」本質,能避免環境變數不生效、函數找不到等常見困擾,是 Linux 開發者必備基本功。
copyright ©
萬盛學電腦網 all rights reserved