全局 vs 用戶、登錄 vs 非登錄、交互 vs 非交互
| 文件 | 作用域 | 觸發時機 | 典型用途 |
/etc/profile | 全局 (所有用戶) | 登錄 Shell (login shell) 啟動時,**一次** | 系統級 PATH、語言、umask、讀取 /etc/profile.d/*.sh |
/etc/bash.bashrc / /etc/bashrc | 全局 | 每次啟動 **交互式非登錄** Bash 時 | 別名、提示符、函數定義 |
~/.bash_profile | 用戶 | 登錄 Shell 啟動時,**一次** | 用戶級環境變量、調用 ~/.bashrc |
~/.bashrc | 用戶 | 每次啟動 **交互式非登錄** Bash 時 | 別名、函數、歷史設置、目錄快捷鍵 |
~/.profile | 用戶 | 登錄 Shell (若無 .bash_profile) | POSIX 兼容、圖形登錄會話 |
~/.bash_logout | 用戶 | 登錄 Shell 退出時 | 清理臨時文件、記錄會話時長 |
加載順序圖解
# 登錄 Shell (如 SSH、TTY、su -)/etc/profile → /etc/profile.d/*.sh → ~/.bash_profile → ~/.bashrc (通常在 .bash_profile 中 source)# 非登錄交互 Shell (如終端標籤、bash 命令)/etc/bash.bashrc → ~/.bashrc# 非交互 Shell (腳本執行)僅讀取 $BASH_ENV 指向的文件 (默認不讀取上述任何文件)
關鍵區別與最佳實踐
- 環境變量 (PATH、JAVA_HOME 等) 放
~/.bash_profile 或 /etc/profile:登錄一次生效,子進程繼承。 - 別名、函數、提示符、歷史控制放
~/.bashrc:每個交互 Shell 重新加載,即時生效。 ~/.bash_profile 必須 source ~/.bashrc:if [ -f ~/.bashrc ]; then . ~/.bashrc; fi
保證登錄 Shell 也能獲得交互配置。 - 系統級修改編輯
/etc/profile.d/custom.sh:避免直接改 /etc/profile 升級覆蓋。 - 圖形登錄 (GDM/LightDM) 讀取
~/.profile:非 Bash 專用,建議在 ~/.profile 中同步 source ~/.bashrc。
驗證技巧
bash -l -c 'echo $PATH' # 模擬登錄 Shell 查看PATHbash -c 'echo $PATH' # 非登錄交互 Shellsource ~/.bashrc && echo $PATH # 手動重載