Linux bash_profile,bashrc,bash_login,profile和bash_logout 的执行顺序
本文将解释以下文件的执行顺序:
- /etc/profile
- ~/.bash_profile
- ~/.bashrc
- ~/.bash_login
- ~/.profile
- ~/.bash_logout
交互式登录shell的执行顺序
以下伪代码解释了这些文件的执行顺序。
execute /etc/profile
IF ~/.bash_profile exists THEN
execute ~/.bash_profile
ELSE
IF ~/.bash_login exist THEN
execute ~/.bash_login
ELSE
IF ~/.profile exist THEN
execute ~/.profile
END IF
END IF
END IF
当您注销交互式 shell 时,以下是执行顺序:
IF ~/.bash_logout exists THEN
execute ~/.bash_logout
END IF
请注意 /etc/bashrc 是由 ~/.bashrc 执行的,如下所示:
# cat ~/.bashrc
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
交互式非登录shell的执行顺序
在启动非登录交互式 shell 时,以下是执行顺序:
IF ~/.bashrc exists THEN
execute ~/.bashrc
END IF
注意:当非交互式 shell 启动时,它会查找 ENV 环境变量,并执行 ENV 变量中提到的 file-name 值。
测试执行顺序
测试执行顺序的方法之一是将不同的 PS1 值添加到这些文件中,然后重新登录到 shell,看看 Linux 提示选择了哪个 PS1 值。此外,前面我们讨论了如何使用 PS1使您的 Linux 提示既实用又时尚。
1. /etc/profile 被执行。将以下 PS1 行添加到 /etc/profile 并重新登录以确保 Linux 提示更改为 /etc/profile 中设置的 PS1 值。
# grep PS1 /etc/profile
PS1="/etc/profile> "
[Note: re-login to see the prompt change as shown below]
Last login: Sat Sep 27 16:43:57 2012 from 192.168.1.2
/etc/profile>
请确保 ~/.bash_profile 没有任何 PS1 才能正常工作。
2. ~/.bash_profile 被执行:在~/.bash_profile、~/.bash_login、~/.profile 和~/.bashrc 中添加以下PS1。重新登录以确保 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> "
[Note: Upon re-login, it executed /etc/profile first and ~/.bash_profile next.
So, it took the PS1 from ~/.bash_profile as shown below.
It also did not execute ~/.bash_login, as ~/.bash_profile exists]
Last login: Sat Sep 27 16:48:11 2012 from 192.168.1.2
~/.bash_profile>
3. ~/.bash_login 被执行。将 .bash_profile 重命名为其他名称。重新登录以确保 Linux 提示更改为 ~/.bash_login 中设置的 PS1 值,如下所示。
~/.bash_profile> mv .bash_profile bash_profile_not_used
[Note: Upon re-login, it executed /etc/profile first.
Since it cannot find ~/.bash_profile, it executed ~/.bash_login]
Last login: Sat Sep 27 16:50:55 2012 from 192.168.1.2
~/bash_login>
4. ~/.profile 被执行。将 .bash_login 重命名为其他名称。重新登录以确保 Linux 提示更改为 ~/.profile 中设置的 PS1 值,如下所示。
~/.bash_login> mv .bash_login bash_login_not_used
[Note: Upon re-login, it executed /etc/profile first.
Since it cannot find ~/.bash_profile and ~/.bash_login, it executed ~/.profile]
Last login: Sat Sep 27 16:56:36 2012 from 192.168.1.2
~/.profile>
5. ~/.bashrc 被执行以进行非登录 shell 测试。在命令提示符下执行“ bash”将给出另一个非登录 shell,它将调用 .bashrc,如下所示。
~/.profile> bash
[Note: This displays PS1 from .bashrc as shown below.]
~/.bashrc> exit
exit
[Note: After exiting from non-login shell, we are back to login shell]
~/.profile>
- 点赞
- 收藏
- 关注作者
评论(0)