Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Windows 綜合教學 >> 關於 Windows

.bash_profile 與 .bashrc 差異詳解:Login Shell 與 Non-login Shell 載入機制完全圖解

編輯:關於 Windows

Linux/Unix 使用者常見疑惑:.bash_profile、.bashrc、/etc/profile、/etc/bashrc 到底差在哪?何時被讀取?變數作用域怎麼分?本文從 Shell 啟動模式切入,徹底釐清配置檔載入順序與繼承關係。

四大核心配置檔職責對照表

檔案路徑適用對象觸發時機主要用途
/etc/profile所有使用者登入 Shell(Login Shell)啟動時,僅執行一次設定全域環境變數(PATH、JAVA_HOME 等)、執行 /etc/profile.d/*.sh
/etc/bashrc(或 /etc/bash.bashrc)所有使用者每次啟動 互動式 Bash Shell 時設定全域別名、提示字元(PS1)、函數等互動環境
~/.bash_profile單一使用者登入 Shell 啟動時,僅執行一次設定用戶級環境變數、通常會 source ~/.bashrc
~/.bashrc單一使用者每次啟動 互動式 Non-login Shell 時設定用戶別名、函數、歷史紀錄、提示字元等互動設定
~/.bash_logout單一使用者登出 Shell 時清理暫存、記錄登出時間等收尾工作

關鍵觀念:Login Shell vs Non-login Shell

  • Login Shell:取得完整登入環境的 Shell。例如:
    文字模式登入(TTY)、SSH 遠端登入、bash --login、su - username。
  • Non-login Shell:繼承現有環境的子 Shell。例如:
    圖形介面終端機(GNOME Terminal、Konsole)、執行 bash、Shell 腳本執行過程(非互動式)。

載入順序流程圖(簡化版)

【Login Shell 啟動】
   ↓
/etc/profile  →  /etc/profile.d/*.sh
   ↓
~/.bash_profile  →  (通常內含) source ~/.bashrc
   ↓
~/.bashrc  →  (可能內含) source /etc/bashrc

【Non-login 互動式 Shell 啟動】
   ↓
~/.bashrc  →  (可能內含) source /etc/bashrc

變數作用域:全域 vs 區域(父子關係)

  • /etc/profile 設定的變數為全域,所有使用者、所有 Shell 皆可繼承。
  • ~/.bashrc、~/.bash_profile 設定的變數為區域(用戶級),僅對該使用者生效,屬於「父子關係」:子 Shell 繼承父 Shell 環境,但修改不回傳父層。

最佳實務建議

  1. 環境變數(PATH、JAVA_HOME、LANG 等) → 寫在 ~/.bash_profile(或 ~/.profile),確保 Login Shell 載入一次即可。
  2. 別名、函數、提示字元、歷史紀錄設定 → 寫在 ~/.bashrc,每次互動式 Shell 皆重新載入。
  3. 在 ~/.bash_profile 末尾加入:
    [[ -f ~/.bashrc ]] && source ~/.bashrc
    確保 Login Shell 也能取得互動式設定。
  4. 系統層級全域設定請修改 /etc/profile.d/custom.sh,避免直接改動 /etc/profile 導致升級覆蓋。

搞懂這套機制,不僅能解決「為什麼我的 alias 在 SSH 進去沒生效」的疑惑,更能打造乾淨、可維護的 Shell 環境。

Copyright © Windows教程網 All Rights Reserved