Bash的功能——执行启动文件

本文详细介绍了Bash作为login shell、交互式shell和非交互式shell时的启动文件执行过程。在login shell启动时,它会执行/etc/profile、~/.bash_profile等文件;交互式shell则执行~/.bashrc;非交互式shell会查找并执行BASH_ENV指定的文件。当使用sh或bash --posix命令时,Bash会进入特定模式,并可能禁止启动文件执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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~/.bashrcBASH_ENV

sh

如果使用名称sh调用Bash,启动文件如下:

交互式shell非交互式shell
login shell/etc/profile, ~/.profile, ENV没有启动文件
非login shellENV没有启动文件

–noprofile选项可用于禁止此login shell的启动文件执行
启动文件执行完后,Bash进入POSIX模式

bash --posix

交互式shell非交互式shell
login shellENV没有启动文件
非login shellENV没有启动文件

被远程shell daemon调用(rshd, sshd)

bashsh
~/.bashrc没有启动文件

调用Bash时,有效用户(组)ID和真实用户(组)ID不一致时

没有启动文件会被执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值