Linux中环境变量优先级
在 Linux 系统中,环境变量的加载和优先级顺序取决于多个文件的作用范围和加载时机。以下是主要的文件及其优先级说明:
1. /etc/profile
作用范围:全局文件,适用于所有用户。
加载时机:登录 Shell 时加载(login shell)。
优先级:最低,通常在用户登录后,首先加载此文件。
2. /etc/bashrc 或 /etc/bash.bashrc
作用范围:全局文件,适用于所有用户。
加载时机:非登录 Shell 时加载(如通过终端打开一个新窗口时)。
优先级:相较于 /etc/profile,优先级稍高,因为它通常由用户的 .bashrc 调用。
3. ~/.bash_profile
作用范围:当前用户。
加载时机:登录 Shell 时加载(如果存在)。
优先级:高于 /etc/profile。
4. ~/.bashrc
作用范围:当前用户。
加载时机:
非登录 Shell 时直接加载。
登录 Shell 时,可能由 ~/.bash_profile 调用。
优先级:高于 /etc/bashrc 和 /etc/profile。
5. ~/.profile
作用范围:当前用户。
加载时机:登录 Shell 时加载(如果 ~/.bash_profile 不存在)。
优先级:低于 ~/.bash_profile。
6. ~/.bash_logout
作用范围:当前用户。
加载时机:用户退出登录 Shell 时加载。
加载优先级总结
系统级:
登录 Shell:/etc/profile → /etc/bashrc。
非登录 Shell:直接加载 /etc/bashrc。
用户级:
登录 Shell:~/.bash_profile → ~/.bashrc → ~/.profile。
非登录 Shell:直接加载 ~/.bashrc。
用户退出时:加载 ~/.bash_logout。
注意事项
登录 Shell 是指通过如 SSH 或 tty 登录系统时的 Shell。
非登录 Shell 是指通过图形界面的终端启动或从一个现有的 Shell 启动子 Shell。
用户文件 (~/.bash_profile, ~/.bashrc 等) 的设置会覆盖系统文件 (/etc/profile, /etc/bashrc) 的设置。

浙公网安备 33010602011771号