跳转至

用户配置文件加载顺序

如果你以 root 用户 登录系统,那么登录时这./bashrc,./profile,/etc/profile,/etc/bashrc四个文件的加载顺序和普通用户类似,但有一些细微差别。以下是具体情况:


1. root 登录时的加载顺序

当你以 登录 shell 的方式以 root 用户登录(例如通过 ssh 登录或切换到 root 执行 su -),加载顺序如下:

  1. 系统级配置文件:
  2. /etc/profile
    这是系统范围的登录 shell 配置文件,所有用户(包括 root)都会加载。

  3. 用户级配置文件:

  4. /root/.bash_profile
    root 用户的专属登录 shell 配置文件。

    • 如果不存在,尝试加载 /root/.bash_login
    • 如果上述文件也不存在,则加载 /root/.profile
  5. 用户级非登录 shell 配置(可能间接加载):

  6. /root/.bashrc
    通常会通过 /root/.bash_profile 加载,例如以下代码:

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

  7. 系统级非登录 shell 配置(间接加载):

  8. /etc/bashrc
    可能由 /etc/profile/root/.bash_profile 引用并加载。

2. 特殊情况:直接切换到 root

如果通过 susudo -i 切换到 root 用户,则加载顺序有所不同:

  • su -(或 sudo -i):
  • 模拟完整的 root 登录环境,加载顺序与上面描述的登录 shell 一致:

    1. /etc/profile
    2. /root/.bash_profile/root/.bash_login/root/.profile
    3. /root/.bashrc(如果手动包含)
    4. /etc/bashrc(间接加载)
  • su(不加 -):

  • 不创建登录 shell,仅加载非登录 shell 的配置文件:
    1. /root/.bashrc
    2. /etc/bashrc

3. 加载文件顺序总结表

场景 加载文件顺序
root 登录 Shell /etc/profile/root/.bash_profile(或 /root/.bash_login,或 /root/.profile
root 非登录 Shell /etc/bashrc/root/.bashrc
su - 切换到 root /etc/profile/root/.bash_profile(或 /root/.bash_login,或 /root/.profile)→ /root/.bashrc/etc/bashrc
su 切换到 root /root/.bashrc/etc/bashrc

4. 文件的功能总结

  • /etc/profile
    系统范围的环境配置,所有登录 shell 会加载。

  • /root/.bash_profile
    root 用户的专属登录 shell 配置,优先级高于 /root/.bash_login/root/.profile

  • /etc/bashrc
    非登录 shell 的系统级配置文件,通常为别名和函数定义。

  • /root/.bashrc
    root 用户的非登录 shell 配置文件,常用于定制环境。


建议

为了确保 root 的配置一致性,可以在 /root/.bash_profile 中手动加载 /root/.bashrc

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

这样无论是登录 shell 还是非登录 shell,都会加载 ~/.bashrc 中的配置,方便管理。