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 時 | 清理暫存、記錄登出時間等收尾工作 |
bash --login、su - username。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
/etc/profile 設定的變數為全域,所有使用者、所有 Shell 皆可繼承。~/.bashrc、~/.bash_profile 設定的變數為區域(用戶級),僅對該使用者生效,屬於「父子關係」:子 Shell 繼承父 Shell 環境,但修改不回傳父層。~/.bash_profile(或 ~/.profile),確保 Login Shell 載入一次即可。~/.bashrc,每次互動式 Shell 皆重新載入。~/.bash_profile 末尾加入:[[ -f ~/.bashrc ]] && source ~/.bashrc/etc/profile.d/custom.sh,避免直接改動 /etc/profile 導致升級覆蓋。搞懂這套機制,不僅能解決「為什麼我的 alias 在 SSH 進去沒生效」的疑惑,更能打造乾淨、可維護的 Shell 環境。
Windows 10 Build 10130 電池顯示改進:圖標放大、亮度四段快捷調節
Win7 檔案總管搜尋記錄清除教學:群組原則徹底關閉或手動刪除單筆記錄
Win10 自带录屏:Win+G 唤起 Xbox Game Bar,支持游戏/应用录制截图
哪些 Lumia 手機可升級 Win10 Mobile?8 款機型完整整理 (含價格、規格、升級時程)
Win10 內建鬧鐘與時鐘 App 完整使用教學:設定鬧鐘、計時器、碼表與世界時鐘
Windows/遊戲執行庫組件補全清單:VC++ 2005/2008/2010、DirectX 9.0c、.NET 3.5/4.0/4.5、OpenAL、PhysX