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 環境變數設定檔完整解析:/etc/profile、~/.bashrc 等 5 大檔案載入順序與適用場景

編輯:Linux 教學

環境變數設定檔層級與載入順序

Linux 登入流程依序讀取下列檔案,後讀取者可覆蓋先前設定:

順序檔案路徑範圍觸發時機典型用途
1/etc/profile全系統所有使用者登入 Shell(Login Shell)啟動時系統預設 PATH、語系、umask、全域別名
2/etc/environment全系統所有使用者PAM 階段(早於 Shell),由 pam_env.so 讀取靜態環境變數(如 JAVA_HOME、http_proxy),不支援指令替換
3~/.profile單一使用者登入 Shell 啟動時(僅執行一次)使用者個人 PATH 補充、啟動 ~/.bashrc、圖形環境變數
4/etc/bash.bashrc (或 /etc/bashrc)所有 Bash 使用者每個互動式 Bash Shell 啟動時系統級別名、提示字元設定、函式定義
5~/.bashrc單一使用者每個互動式 Bash Shell 啟動時個人別名、函式、歷史紀錄設定、提示字元客製化

關鍵區別:Login Shell vs. Non-login Shell

  • Login Shell:文字模式登入、SSH 登入、su - username、圖形登入(由 Display Manager 呼叫)。會讀取 /etc/profile → ~/.profile。
  • Non-login 互動式 Shell:終端機視窗、bash、su username(不帶 -)。不讀取 /etc/profile、~/.profile,僅讀取 /etc/bash.bashrc → ~/.bashrc。
  • Non-interactive Shell:執行 Shell 腳本(#!/bin/bash)。不讀取 以上任何設定檔(除非腳本內 source)。

最佳實踐建議

  1. 環境變數(PATH、JAVA_HOME、LANG):放在 ~/.profile(登入一次即可)或 /etc/environment(系統級靜態值)。
  2. 別名、函式、提示字元、歷史紀錄:放在 ~/.bashrc(每個終端機皆生效)。
  3. ~/.profile 應包含:
# 載入 ~/.bashrc(若存在)
if [ -n "$BASH_VERSION" ]; then
  if [ -f "$HOME/.bashrc" ]; then
    . "$HOME/.bashrc"
  fi
fi

# 個人 bin 目錄加入 PATH
if [ -d "$HOME/bin" ]; then
  PATH="$HOME/bin:$PATH"
fi

常見錯誤與除錯

  • 重複加入 PATH:每開啟一個終端機 PATH 變長。解決:在 ~/.bashrc 判斷是否已存在再加入,或改放 ~/.profile。
  • 圖形環境不生效:部分 Display Manager 不讀取 ~/.profile。解決:設定 ~/.xprofile 或 ~/.xsessionrc,或修改 /etc/environment。
  • 腳本中環境變數失效:腳本非互動式 Shell。解決:腳本開頭 source /etc/profile 或 source ~/.profile,或改用 systemd 服務的 EnvironmentFile。

Zsh/Fish 使用者注意

  • Zsh:/etc/zsh/zprofile → ~/.zprofile(Login)、/etc/zsh/zshrc → ~/.zshrc(互動式)。
  • Fish:/etc/fish/config.fish → ~/.config/fish/config.fish(所有實例),無 Login/Non-login 區分。
Copyright © Windows教程網 All Rights Reserved