13. bash 启动文件
对于交互式 Bash Shell
以下是当您通过 Bash 交互式 shell 登录时 bash 启动文件的执行顺序:
- 如果
/etc/profile存在,则执行并进入下一步 - 如果
~/.bash_profile存在,则执行并走到最后 - 如果
~/.bash_login存在, 则执行并走到最后 - 如果
~/.profile存在, 则执行并走到最后
在上述步骤中,bash 在登录 shell 期间不会直接检查~/.bashrc。
但是,在~/.bash_profile文件中,顶部通常包含以下代码,它将在登录 shell 期间调用~/.bashrc。
如果~/.bash_profile中没有以下行,请添加它们。
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
当执行/etc/profile时,它会检查/etc/profile.d下的所有*.sh文件并执行它们。
如果您是系统管理员,并且想要为所有用户添加一些全局环境变量设置,您可以在/etc/profile.d目录下创建一个名为env.sh的 shell 脚本。
当你注销时,如果~/.bash_logout退出,它就会在那时执行它。
对于交互式非登录 Bash Shell
对于 Bash 交互式非登录 shell,如果~/.bashrc存在,则执行它。
通常,您将在~/.bashrc中包含以下几行,它将执行 /etc/bashrc。如果没有,请添加它们。
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
测试执行顺序
测试执行顺序的方法之一是向这些文件添加不同的
PS1
值,然后再次登录到 shell 以查看 Linux 提示符选择了哪个
PS1
值。
前面我们讨论了如何使用
PS1
让您的 Linux 提示符既实用又时尚。
/etc/profile
将以下
PS1
行添加到/etc/profile并重新登录,以确保 Linux 提示符更改为/etc/profile中设置的
PS1
值。
$ grep PS1 /etc/profile
PS1="/etc/profile> "
重新登录即可看到提示符变化如下图。 请确保~/.bash_profile没有任何
PS1
才能正常工作。
/etc/profile>
~/.bash_profile
将以下
PS1
添加到~/.bash_profile、~/.bash_login、~/.profile和~/.bashrc。
重新登录以确保 Linux 提示符更改为~/.bash_profile中设置的
PS1
值,如下所示。
/etc/profile> grep PS1 ~/.bash_profile
export PS1="~/.bash_profile> "
/etc/profile> grep PS1 ~/.bash_login
export PS1="~/.bash_login> "
/etc/profile> grep PS1 ~/.profile
export PS1="~/.profile> "
/etc/profile> grep PS1 ~/.bashrc
export PS1="~/.bashrc> "
重新登录后,bash 首先执行/etc/profile,然后执行~/.bash_profile。
因此,它从~/.bash_profile中获取了 PS1,如下所示。
它也没有执行 ~/.bash_login,因为~/.bash_profile存在。
~/.bash_profile>
~/.bash_login
将 .bash_profile 重命名为其他名称。 重新登录以确保 Linux 提示符更改为~/.bash_login中设置的
PS1
值,如下所示。
mv .bash_profile bash_profile_not_used
重新登录时,它首先执行/etc/profile。 由于找不到~/.bash_profile,所以它执行 ~/.bash_login。
~/bash_login>
~/.profile
.bash_login 重命名为其他名称。 重新登录以确保 Linux 提示符更改为~/.profile中设置的
PS1
值,如下所示。
~/.bash_login> mv .bash_login bash_login_not_used
重新登录时,它首先执行/etc/profile。 由于找不到~/.bash_profile和 ~/.bash_login,所以它执行了~/.profile。
~/.profile>
~/.bashrc (non-login)
~/.bashrc被执行用于非登录 shell。
在命令提示符处执行 bash将给出另一个非登录 shell,它将调用.bashrc,如下所示。
~/.profile> bash
这将显示.bashrc中的
PS1
,如下所示。
~/.bashrc> exit
从非登录 shell 退出后,我们回到登录 shell。
~/.profile>