Linux 環境變數分為系統級(全域)與用戶級(局部),對應不同配置檔案與載入時機。搞清檔案層級、載入順序、生效範圍,才能精準控制變數作用域,避免「改了不生效」或「汙染全域環境」。本文系統整理核心配置檔、載入流程、修改範例與避坑指南。
| 層級 | 檔案路徑 | 生效範圍 | 載入時機 | 備註 |
|---|---|---|---|---|
| 系統級 | /etc/profile | 所有用戶 | 登入 Shell(login shell)啟動時,僅執行一次 | 全域環境變數、PATH 基礎值 |
| /etc/bashrc | 所有用戶 | 每次啟動 互動式非登入 Shell | 別名、函數、提示符設定 | |
| 用戶級 | ~/.bash_profile | 當前用戶 | 登入 Shell,僅執行一次(按優先序擇一執行) | 優先序:.bash_profile > .bash_login > .profile |
| ~/.bash_login | 當前用戶 | 登入 Shell | 若 .bash_profile 不存在則執行 | |
| ~/.profile | 當前用戶 | 登入 Shell | Ubuntu/Debian 預設唯一用戶級登入檔 | |
| ~/.bashrc | 當前用戶 | 每次啟動 互動式非登入 Shell | 別名、函數、提示符、建議放用戶自訂變數 | |
| ~/.bash_logout | 當前用戶 | 登出 Shell 時 | 清理暫存、備份歷史等 |
登入 Shell (login shell)
│
├─ /etc/profile (系統級,必讀)
│
├─ ~/.bash_profile → 若無則 ~/.bash_login → 若無則 ~/.profile (用戶級,擇一讀取)
│ │
│ └─ 通常在內部 source ~/.bashrc
│
非登入互動 Shell (interactive non-login)
│
├─ /etc/bashrc (系統級)
│
└─ ~/.bashrc (用戶級)
非互動 Shell (腳本執行)
│
└─ 讀取 $BASH_ENV 指定檔案(若設定)
vi /etc/profile
# 末尾添加
export PATH=$PATH:/opt/myapp/bin
# 立即生效
source /etc/profile
vi ~/.bashrc
# 末尾添加(注意追加而非覆蓋 PATH)
export PATH=$PATH:$HOME/.local/bin
export MY_TOOL_HOME=$HOME/tools/mytool
# 立即生效
source ~/.bashrc
# 錯誤:覆蓋系統 PATH
PATH=/my/path
# 正確:保留原值並追加
PATH=$PATH:/my/path
# 或
export PATH=${PATH}:/my/path
source /etc/profile 或 . /etc/profile:當前 Shell 進程內生效(推薦)。sh /etc/profile:在子 Shell執行,變數不會傳回父 Shell,**不生效**。.bashrc/.profile)後,開啟新終端分頁/視窗即可生效,無需重啟系統。echo $VAR 以最近載入者為準。
# 查看變數來源
grep -r "MY_VAR" /etc/profile /etc/bashrc ~/.bash_profile ~/.bashrc ~/.profile 2>/dev/null
# 對比不同 Shell 類型
bash -c 'echo $MY_VAR' # non-login interactive
bash -l -c 'echo $MY_VAR' # login shell
ssh localhost 'echo $MY_VAR' # remote login shell
遵循「系統級改 /etc/profile、用戶級改 ~/.bashrc、追加 PATH、source 立即生效」四大原則,環境變數配置將不再是謎題。建立個人 ~/.env.local 集中管理私有變數,在 .bashrc 末尾 source ~/.env.local,進一步實現配置與邏輯分離。