萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux 環境變數設定檔完整解析:/etc/profile、~/.bashrc、~/.profile 載入順序與差異

環境變數與 Shell 的關係

登入系統後啟動 Shell(預設 bash),環境變數透過 Shell 設定,子進程繼承父進程環境。設定檔分為系統級(影響所有使用者)與使用者級(僅影響該使用者)。

系統級設定檔

檔案觸發時機用途
/etc/profile登入 Shell 啟動時全域環境變數、PATH、umask、啟動 /etc/profile.d/*.sh
/etc/bash.bashrc互動式非登入 bash 啟動時全域別名、提示字元、函式、bash 專用設定
/etc/environmentPAM session 階段(早於 Shell)純 KEY=VALUE 格式,不支援邏輯,影響所有登入方式

使用者級設定檔(依載入順序)

檔案Shell 類型載入條件備註
~/.bash_profilebash登入 Shell(第一個存在即停止尋找)通常 source ~/.bashrc
~/.bash_loginbash登入 Shell(若無 .bash_profile)較少用
~/.profilesh 相容登入 Shell(若無上述兩者)Ubuntu 預設只有此檔
~/.bashrcbash互動式非登入 Shell別名、函式、提示字元
~/.bash_logoutbash登出登入 Shell 時清理暫存、記錄

載入流程圖解

登入 (SSH/Console/GUI 登入)
   │
   ├─→ /etc/profile
   │      └─→ /etc/profile.d/*.sh
   │
   ├─→ ~/.bash_profile  (存在即執行,否則嘗試)
   │      └─→ ~/.bashrc  (通常在這裡 source)
   ├─→ ~/.bash_login    (無 .bash_profile 時)
   └─→ ~/.profile       (無前兩者時)

互動式非登入 (開新終端機視窗、bash -i)
   │
   └─→ ~/.bashrc
        └─→ /etc/bash.bashrc (若 bashrc 內 source)

非互動式 (執行腳本 ./script.sh)
   │
   └─→ $BASH_ENV 指定檔案 (預設不載入上述檔案)

實務設定建議

1. 個人環境變數:編輯 ~/.profile 或 ~/.bash_profile

export PATH="$HOME/.local/bin:$PATH"
export EDITOR=vim
export LANG=zh_TW.UTF-8

2. 互動式設定(別名、提示字元、函式):編輯 ~/.bashrc

alias ll='ls -alF'
alias gs='git status'
PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

3. 在 ~/.bash_profile 中載入 ~/.bashrc

if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

4. 修改 PATH 正確寫法

# 錯誤:PATH=/new/path  → 覆蓋原有 PATH
# 正確:
PATH="$PATH:/new/path"
# 或
export PATH="/new/path:$PATH"

立即生效

source ~/.bashrc        # 當前 Shell 生效
# 或
. ~/.profile

常見問題

  • CRON 執行找不到指令:cron 非互動式非登入 Shell,需在腳本開頭 source ~/.profile 或使用完整路徑
  • sudo 環境變數遺失:sudo -E 保留環境,或在 /etc/sudoers 設定 Defaults env_keep += "VAR"
  • GUI 登入不讀取 .bashrc:桌面環境由 PAM/Display Manager 啟動,環境變數請設定於 ~/.profile 或 /etc/environment

Zsh / Fish 使用者

  • Zsh:~/.zprofile(登入)、~/.zshrc(互動式)
  • Fish:~/.config/fish/config.fish(通用)、~/.config/fish/conf.d/
copyright © 萬盛學電腦網 all rights reserved