login shell
如果Bash作为login shell调用时,它按顺序读取和执行以下文件中的命令:
- /etc/profile(如果存在)
- ~/.bash_profile
- ~/.bash_login
- ~/.profile
通常,在/etc/profile里有这么一句:
if [ -d /etc/profile.d ]; then
for i in /etc/profile.d/*.sh; do
if [ -r $i ]; then
. $i
fi
done
unset i
fi
所以,/etc/profile.d目录下的*.sh文件也会在login shell启动时被执行
如果调用Bash时使用了–noprofile选项,上述文件就不会在login shell启动时执行。
login shell退出时会执行
- ~/.bash_logout(如果存在)
非login shell,交互式shell
如果Bash作为交互式shell,但不是login shell调用时,读取和执行下面文件中的命令
- ~/.bashrc
如果调用Bash时使用了–norc选项,上述文件就交互式shell启动时执行。
使用–rcfile file选项指定交互式shell启动时执行的文件,而不是~/.bashrc
通常,在login shell的启动文件~/.bash_profile, ~/.bash_login和~/.profile里有这么一句:
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
所以- ~/.bashrc也在login shell启动时被执行
非交互式shell
以非交互方式启动Bash时(例如运行shell脚本),Bash还会环境中查找变量BASH_ENV,如果BASH_ENV存在,则会对其进行扩展,并将扩展后的值用作要读取和执行的文件。Bash的行为就像执行以下命令一样:
if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
但PATH变量的值不用于搜索文件名。
总结一下:
交互式shell | 非交互式shell | |
---|---|---|
login shell | /etc/profile, ~/.bash_profile, ~/.bash_login, ~/.profile, ~/.bashrc | /etc/profile, ~/.bash_profile, ~/.bash_login, ~/.profile, BASH_ENV |
非login shell | ~/.bashrc | BASH_ENV |
sh
如果使用名称sh调用Bash,启动文件如下:
交互式shell | 非交互式shell | |
---|---|---|
login shell | /etc/profile, ~/.profile, ENV | 没有启动文件 |
非login shell | ENV | 没有启动文件 |
–noprofile选项可用于禁止此login shell的启动文件执行
启动文件执行完后,Bash进入POSIX模式
bash --posix
交互式shell | 非交互式shell | |
---|---|---|
login shell | ENV | 没有启动文件 |
非login shell | ENV | 没有启动文件 |
被远程shell daemon调用(rshd, sshd)
bash | sh |
---|---|
~/.bashrc | 没有启动文件 |
调用Bash时,有效用户(组)ID和真实用户(组)ID不一致时
没有启动文件会被执行