CentOS系統(tǒng)環(huán)境變量配置指南
系統(tǒng)級環(huán)境變量配置
1. /etc/profile全局配置
修改系統(tǒng)全局配置文件適用于所有用戶:
sudo vim /etc/profile
# 在文件末尾添加(示例):
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk
export PATH=$PATH:$JAVA_HOME/bin
保存后執(zhí)行source /etc/profile
立即生效
2. /etc/profile.d/獨立腳本
創(chuàng)建獨立配置文件便于模塊化管理:
sudo vim /etc/profile.d/custom_env.sh
# 添加環(huán)境變量定義
export CUSTOM_PATH=/opt/myapp/bin
腳本權限需設置為可執(zhí)行:chmod +x /etc/profile.d/custom_env.sh
用戶級環(huán)境變量配置
1. ~/.bashrc用戶配置
vim ~/.bashrc
# 添加用戶特定配置
alias ll='ls -alh'
export USER_LOG_DIR=/var/log/myapp
當前終端即時生效:source ~/.bashrc
2. ~/.bash_profile登錄配置
針對登錄會話的環(huán)境變量設置:
vim ~/.bash_profile
# 添加登錄時執(zhí)行的配置
export TMOUT=3600 # 設置終端超時時間
驗證配置效果
查看特定環(huán)境變量:
echo $JAVA_HOME
printenv PATH
驗證配置持久性:重啟終端或系統(tǒng)后檢查變量值
臨時環(huán)境變量設置
會話級臨時配置(關閉終端后失效):
export TEMP_VAR="test_value"
env | grep TEMP_VAR
配置文件優(yōu)先級
- /etc/profile → /etc/profile.d/*.sh → ~/.bash_profile → ~/.bashrc
- 非登錄終端僅加載~/.bashrc