草依山的Javascript世界

一个Javascript程序猿的学习纪录剩地,不仅仅是JS,还有Linux、Mac、nodeJs、吃、玩!

[翻译]bash的各种文件载入执行顺序

[注] 一直以来都没有搞清楚 bash 里各种文件的载入顺序,这是一篇好文,顺手翻译一下。

这篇文章解释了下面这些文件载入执行的顺序:

  • /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 环境变量标识的文件名

测试执行顺序

测试执行顺序的一个方法是给这些文件添加不同的 PS1 值,然后重新登录 shell,看看都有哪些值被显示出来。我们之前有讨论过如何使用 PS1 来使你的 Linux 提示符即好看又实用。

  1. /etc/profile 被执行。 添加下面的 PS1 行到 /etc/profile 然后重新登录,确保提示符已经变成了这个文件里设置的样子。
# 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 2008 from 192.168.1.2
/etc/profile>

为了保证正常执行,需要确保 ~/.bash_profile 里没有别的 PS1 赋值。

  1. ~/.bash_profile 被执行: 添加下面的 PS1 到 ~/.bash_profile, ~/.bash_login, ~/.profile and ~/.bashrc。 重新登录一下,确认提示符像下面这样变成了 ~/.bash_profile 里设置的内容。
/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> "

[注意: 由于重新登录, 先执行 /etc/profile 然后 ~/.bash_profile。
所以 PS1 会是  ~/.bash_profile 里设置的.
由于 ~/.bash_profile 的存在, 它不会执行  ~/.bash_login ]
Last login: Sat Sep 27 16:48:11 2008 from 192.168.1.2
~/.bash_profile>
  1. ~/.bash_login 被执行。 把 .bash_profile 重命名一下。重新登录确认提示符像下面这样变成 ~/.bash_login 里设置的。
~/.bash_profile> mv .bash_profile bash_profile_not_used

[注意: 由于重新登录,它先执行 `/etc/profile`。
同时由于找不到 `~/.bash_profile`, 它执行 `~/.bash_login`]
Last login: Sat Sep 27 16:50:55 2008 from 192.168.1.2
~/bash_login>
  1. ~/.profile 被执行。重命名 .bash_login。重新登录确认提示符像下面这样变成了 ~/.profile 里设置的。
~/.bash_login> mv .bash_login bash_login_not_used

[注意: 由于重新登录,它先执行 `/etc/profile`。
同时由于找不到 `~/.bash_profile` 和 `~/.bash_login`, 它执行 `~/.profile`]
Last login: Sat Sep 27 16:56:36 2008 from 192.168.1.2
~/.profile>
  1. ~/.bashrc 被非登录执行。 在终端里执行 bash,将会产生一个非登录shell,它会执行 .bashrc
~/.profile> bash

[注意: 下面显示的 PS1 来自 `.bashrc`。 ]
~/.bashrc> exit
exit

[注意: 从非登录 shell 里退出后,回到登录后的 shell]
~/.profile>
文章地址: [翻译]bash的各种文件载入执行顺序
欢迎关注我的微博与我交流:@草依山
Github上也有一些东西:[Github]
所有文章坚决抵制jb51.net的转载!
标签: shell 1
2016-09-29

相关文章

2019-09-30 深度神经网络入门
2017-03-22 一次算PI的小尝试
2017-02-13 new做了些什么
2016-05-31 phantomjs在linux下截图中文字体问题
2016-04-24 Promise的错误处理

文章修改纪录

加载中...
Copyright © 2013. Create By 草依山, Fork