Shell 启动文件规范整理
Shell 启动文件规范整理
一、POSIX / IEEE Std 1003.1(sh 系基线)
POSIX 规定的 sh 启动仅 3 个加载点:
| 阶段 | 文件 |
|---|---|
| 登录 shell | /etc/profile |
| 登录 shell | ~/.profile |
| 非交互式 shell | $ENV 指向的文件 |
注意:
~/.bashrc、~/.bash_profile、/etc/bash.bashrc不属于 POSIX 标准,是 bash 的扩展实现。
二、Bash 参考手册 §Invocation(bash 扩展,man bash INVOCATION 章节)
登录 shell(bash --login / ssh 登录等)
执行顺序:
/etc/profile(若存在)~/.bash_profile(若存在)~/.bash_login(#2 不存在时读取)~/.profile(#2、#3 都不存在时读取)
退出时:
5. ~/.bash_logout(若存在)
交互式非登录 shell(普通终端、tmux 新窗口)
/etc/bash.bashrc(若存在;Debian/Ubuntu 约定)~/.bashrc(若存在)
说明:bash 手册不强制系统必须存在
/etc/bash.bashrc,规则为“如果存在就读取”,该文件是 Debian 系发行版的约定。
非交互式 shell(直接执行脚本)
$BASH_ENV指向的文件(若已设置环境变量)
setuid 执行场景
- 依次读取:
/etc/profile→~/.bash_profile→~/.bash_login→~/.profile - 不会读取
~/.bashrc,也不会读取$BASH_ENV
三、FHS 3.0(文件系统层级标准)
FHS §3.7.2:只规定文件存放位置,不规定哪些场景读取,读取逻辑由 POSIX/bash 手册定义。
| 路径 | 用途说明 |
|---|---|
/etc/profile |
系统级登录环境 |
/etc/bash.bashrc |
系统级 bash 交互环境(Debian 命名) |
/etc/profile.d/ |
系统级登录扩展,存放 *.sh 片段 |
/etc/bash.bash_logout |
系统级登出脚本(Debian 约定) |
~/.bash_profile |
用户级登录环境(bash 专用) |
~/.bash_login |
用户级登录环境(bash 专用) |
~/.bashrc |
用户级 bash 交互环境 |
~/.bash_logout |
用户级登出脚本 |
~/.profile |
用户级登录环境(POSIX/ksh/sh 通用) |
四、发行版策略
| 文档 | 内容要点 |
|---|---|
| Debian Policy Manual §9.11 | /etc/profile.d/*.sh:必须带 .sh 后缀;两位数字前缀控制加载顺序;脚本自洽、禁止输出;退出码必须为 0 |
| Fedora/Red Hat Packaging Guidelines §Scriptlets | /etc/profile.d/ 脚本约定,与 Debian 思路类似 |
| LSB §21.4(已废弃,2015 终止,仍有历史影响) | /etc/profile.d/ 脚本排序约定来源 |
| Ubuntu/Debian bash.bashrc 头部注释 | 注释说明:该文件也需要被 login shell 在 /etc/profile 中 source;对应机器 /etc/profile 内代码: if [ -f /etc/bash.bashrc ]; then . /etc/bash.bashrc; fi |
浙公网安备 33010602011771号