在 CentOS(以及大多数 Linux 发行版) 中,env(环境变量)的加载顺序主要取决于 登录方式(login / non-login、interactive / non-interactive) 和 使用的 shell(默认是 bash)。下面以 CentOS 7/8 使用 bash 为主进行说明。
典型场景:
ssh user@hostsu - user加载顺序:
/etc/profile
↓
/etc/profile.d/*.sh
↓
~/.bash_profile
↓
~/.bash_login
↓
~/.profile
只加载 第一个存在且可读的文件
典型场景:
su user(不带 -)加载顺序:
/etc/bashrc
↓
~/.bashrc
典型场景:
bash test.sh加载顺序:
$BASH_ENV
如果没有设置 BASH_ENV,通常不加载任何 profile 或 bashrc
| 文件 | 作用范围 | 说明 |
|---|---|---|
/etc/profile |
全局 | 登录 shell 统一配置 |
/etc/profile.d/*.sh |
全局 | 模块化环境变量(推荐) |
~/.bash_profile |
用户级 | 登录 shell |
~/.bash_login |
用户级 | 登录 shell(较少用) |
~/.profile |
用户级 | 兼容 sh |
/etc/bashrc |
全局 | 非登录交互式 shell |
~/.bashrc |
用户级 | 非登录交互式 shell |
$BASH_ENV |
非交互 | 脚本执行前加载 |
~/.bash_profile 通常包含:if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
✅ 所以 登录 shell 也会加载 ~/.bashrc
~/.bashrc 通常包含:if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
✅ 所以 bashrc 也会加载系统级 bashrc
| 命令 | 类型 | 加载内容 |
|---|---|---|
su user |
非登录 | ~/.bashrc |
su - user |
登录 | /etc/profile → ~/.bash_profile |
✅ 生产环境推荐 su -
Login Shell
├── /etc/profile
│ └── /etc/profile.d/*.sh
└── ~/.bash_profile
└── ~/.bashrc
└── /etc/bashrc
Interactive Non-Login
├── /etc/bashrc
└── ~/.bashrc
Non-Interactive
└── $BASH_ENV
~/.bashrc 但没被 login shell 加载/etc/profile.d/*.sh 但文件没 .sh 后缀✅ 解决方案:
# 推荐
/etc/profile.d/myenv.sh
✅ 解决:
source /etc/profile
CentOS 中 env 加载顺序由 shell 类型决定:
- 登录 shell →
/etc/profile→~/.bash_profile- 交互非登录 →
~/.bashrc- 脚本执行 →
$BASH_ENV
如果你愿意,我可以帮你画一张 CentOS 7/8 systemd + bash 的完整环境变量加载流程图,或者针对 Docker / cron / sudo 场景单独说明。