萬盛學電腦網

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

Linux 環境變數配置檔案載入順序與作用域深度解析

五大配置檔案功能定位

檔案作用域載入時機執行方式典型用途
/etc/environment全系統所有進程登入最早(PAM)KEY=VALUE 靜態賦值PATH, JAVA_HOME, 語系等全域變數
/etc/profile所有用戶登入 Shell登入 Shell 啟動腳本執行全域環境、umask、別名、函數
~/.profile當前用戶登入 Shell登入 Shell 啟動(次序 2)腳本執行用戶個人環境、PATH 擴充
/etc/bash.bashrc所有用戶互動 Shell每次開啟 Bash 互動 Shell腳本執行提示符、別名、函數、歷史設定
~/.bashrc當前用戶互動 Shell每次開啟 Bash 互動 Shell腳本執行個人別名、函數、提示符客製化

載入順序驗證實驗

實驗設計

# 在各檔案加入追蹤碼
# /etc/environment
ENV_MSG="this is /etc/environment"

# /etc/profile
echo $ENV_MSG >> /home/xyz/log.txt
echo "this is /etc/profile" >> /home/xyz/log.txt

# ~/.profile
echo "this is .profile" >> /home/xyz/log.txt

# /etc/bash.bashrc
echo "this is /etc/bash.bashrc" >> /home/xyz/log.txt

# ~/.bashrc
echo "this is .bashrc" >> /home/xyz/log.txt

實驗結果

# 開機登入後 log.txt 內容:
this is /etc/environment
this is /etc/profile
this is .profile

# 開啟終端機後新增:
this is /etc/bash.bashrc
this is .bashrc

# 再開一個終端機:
this is /etc/bash.bashrc
this is .bashrc  (再次執行)

# 註冊重登:
this is /etc/environment
this is /etc/profile
this is .profile
this is /etc/bash.bashrc
this is .bashrc

# Ctrl+Alt+F1 文字主控台登入:
this is /etc/bash.bashrc
this is /etc/environment
this is /etc/profile
this is .bashrc
this is .profile

關鍵結論

  1. 登入流程:/etc/environment → /etc/profile → ~/.profile(僅登入 Shell 執行一次)
  2. 互動 Shell:/etc/bash.bashrc → ~/.bashrc(每次開啟終端機都執行)
  3. /etc/environment 非腳本:不支援邏輯判斷、變數引用、命令替換,純 KEY=VALUE
  4. 文字主控台:載入順序不同,.bashrc 可能先於 .profile

最佳實踐建議

全域環境變數(所有用戶、所有進程)

# /etc/environment
JAVA_HOME=/usr/lib/jvm/java-11
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
LANG=zh_TW.UTF-8

登入 Shell 邏輯(所有用戶)

# /etc/profile
export PATH=$PATH:/opt/scripts
umask 022
# 來源 /etc/profile.d/*.sh 模組化管理

用戶個人環境(登入 Shell)

# ~/.profile
export PATH=$HOME/bin:$HOME/.local/bin:$PATH
# 載入 .bashrc(若為 Bash)
if [ -n "$BASH_VERSION" ]; then
    [ -f ~/.bashrc ] && . ~/.bashrc
fi

互動 Shell 客製化(每次終端機)

# ~/.bashrc
# 僅互動模式執行
case $- in *i*) ;; *) return ;; esac

# 歷史設定
HISTSIZE=10000
HISTFILESIZE=20000
HISTCONTROL=ignoreboth:erasedups

# 別名
alias ll='ls -alF'
alias grep='grep --color=auto'

# 提示符
PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\]\$ '

# 函數
mkcd() { mkdir -p "$1" && cd "$1"; }

系統級 Bash 設定

# /etc/bash.bashrc
# 系統級別名、函數、提示符基準

常見錯誤與避坑

systemd 服務環境變數

# /etc/systemd/system/myservice.service
[Service]
Environment=VAR1=value1
EnvironmentFile=/etc/myservice/env
# 或
systemctl edit myservice  # 覆寫單元
copyright © 萬盛學電腦網 all rights reserved
錯誤做法後果正確做法
在 /etc/environment 用 $VAR 引用字面字串不解析寫死完整路徑或用 /etc/profile
在 .bashrc 設定 PATH 重複疊加PATH 變超長、效能下降用條件判斷或放在 .profile
.bashrc 輸出文字(echo)破壞 SCP/SFTP/非互動連線僅在互動模式輸出
修改後未重新登入/重開終端不生效source 對應檔案或重新登入