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

Bash 配置文件加載順序與作用域詳細解析

編輯:Linux 教學

核心配置文件對照表

文件作用範圍觸發時機備註
/etc/profile 全域(所有用戶) 登入 Shell 時 會讀取 /etc/profile.d/*.sh
/etc/bashrc 全域 每次啟動互動式 Bash 非登入 Shell 也會讀取
~/.bash_profile 用戶級 登入 Shell 時(僅一次) 通常調用 ~/.bashrc
~/.bashrc 用戶級 每次啟動互動式 Shell 含別名、函數、提示符等
~/.bash_logout 用戶級 退出登入 Shell 時 清理臨時任務用

關鍵區別:Login vs Non-login Shell

  • Login Shell:su - user、SSH 登入、TTY 登入 → 讀取 ~/.bash_profile
  • Non-login 互動式 Shell:終端模擬器新分頁、bash 命令 → 讀取 ~/.bashrc

父子關係與變量繼承

/etc/profile 設定的全域變量對所有用戶生效;~/.bashrc 等用戶級配置只能繼承父級變量,屬「父子關係」。

最佳實踐建議

# ~/.bash_profile 典型內容
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# 環境變量放在 ~/.bash_profile 或 ~/.profile
export PATH="$HOME/bin:$PATH"
export EDITOR=vim

將別名、函數、提示符等互動式配置集中在 ~/.bashrc,環境變量放在 ~/.bash_profile,並由前者調用後者,避免重複維護。

Copyright © Windows教程網 All Rights Reserved