温馨提示×

CentOS env加载顺序是什么

小樊
35
2026-07-09 06:18:35
栏目: 智能运维

CentOS(以及大多数 Linux 发行版) 中,env(环境变量)的加载顺序主要取决于 登录方式(login / non-login、interactive / non-interactive)使用的 shell(默认是 bash)。下面以 CentOS 7/8 使用 bash 为主进行说明。


一、先说结论(重点)

✅ 登录顺序(最常见)

1️⃣ 登录 shell(Login Shell)

典型场景:

  • 本地终端登录
  • ssh user@host
  • su - user

加载顺序:

/etc/profile
    ↓
/etc/profile.d/*.sh
    ↓
~/.bash_profile
    ↓
~/.bash_login
    ↓
~/.profile

只加载 第一个存在且可读的文件


2️⃣ 非登录交互式 shell(Interactive Non-Login)

典型场景:

  • 已登录后打开新终端(GNOME Terminal)
  • su user(不带 -

加载顺序:

/etc/bashrc
    ↓
~/.bashrc

3️⃣ 非交互式 shell(Non-Interactive)

典型场景:

  • 执行脚本:bash test.sh
  • cron 任务

加载顺序:

$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 非交互 脚本执行前加载

三、CentOS 中的典型调用关系(很重要)

1️⃣ ~/.bash_profile 通常包含:

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

✅ 所以 登录 shell 也会加载 ~/.bashrc


2️⃣ ~/.bashrc 通常包含:

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

✅ 所以 bashrc 也会加载系统级 bashrc


四、su 的区别(非常容易混淆)

命令 类型 加载内容
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

六、常见排错建议

❓ 为什么 ssh 登录后环境变量不生效?

  • 变量写在 ~/.bashrc 但没被 login shell 加载
  • 或写在 /etc/profile.d/*.sh 但文件没 .sh 后缀

✅ 解决方案:

# 推荐
/etc/profile.d/myenv.sh

❓ cron 里为什么没有环境变量?

  • cron 是 非交互、非登录
  • 不加载 bashrc / profile

✅ 解决:

  • 在脚本里手动 source
source /etc/profile

七、一句话总结

CentOS 中 env 加载顺序由 shell 类型决定:

  • 登录 shell/etc/profile~/.bash_profile
  • 交互非登录~/.bashrc
  • 脚本执行$BASH_ENV

如果你愿意,我可以帮你画一张 CentOS 7/8 systemd + bash 的完整环境变量加载流程图,或者针对 Docker / cron / sudo 场景单独说明。

0