|
发表于 2004-8-15 17:03:42
|
显示全部楼层
回复: bash配置文件实验报告
最初由 windrose 发表
前一段时间,有兄弟提出为什么打开终端后.bashrc文件没有被执行,结果引发了一场讨论。详见:http://www.linuxsir.cn/forum.php?mod=viewthread&tid=69247
近来用man bash看了看bash的文档,其中在Files部分提到:
- /etc/profile
- The systemwide initialization file, executed for login shells
- 系统全程的初始化文件,为登录的shell所执行
- ~/.bash_profile
- The personal initialization file, executed for login shells
- 个人的初始化文件,为登录的shell所执行
- ~/.bashrc
- The individual per-interactive-shell startup file
- 个人的交互式shell的起始文件
- ~/.bash_logout
- The individual login shell cleanup file, executed when a login shell exits
- 个人登录shell的清理文件,当登录shell退出时执行
复制代码
文档的Invocation部分详细解释了在哪种情况下调用哪个配置文件,其中提到如果用sh命令来调用bash时还可能会用到 ~/.profile 文件。
为了直观理解manpage中提到的各种情况,我设计了几个简单的实验来进行验证。
第一步:建立各个对应文件,即在用户目录下分别建立 .bash_profile, .profile, .bashrc和 .bash_logout。假如已经有这些文件了,请先做好备份。每个文件的内容只有一行,命令如下:
- echo 'echo hello from .bash_profile' > .bash_profile
- echo 'echo hello from .profile' > .profile
- echo 'echo hello from .bashrc' > .bashrc
- echo 'echo hello from .bash_logout' > .bash_logout
复制代码
第二步:设置用文本界面启动,用root身份编辑 /etc/inittab文件,把以id开头的一行改为:
id:3:initdefault:
第三步:退出当前用户,此时会进入文本登录界面。
实验一:
1.输入用户名和密码进行登录。
根据bash的manpage,此时启动的是登录shell,bash将首先执行/etc/profile文件,然后依次查找 ~/.bash_profile, ~/.bash_login, ~/.profile文件,并执行它所找到的第一个。在我们当前的实验中,它应该执行的是 .bash_profile,因此屏幕应该显示 hello from .bash_profile
2.输入:
logout
屏幕应显示 hello from .bash_logout。由于当前是个登录shell,所以退出时会执行 .bash_logout
实验二:
1.在文本登录界面登录,然后输入命令:
sh
屏幕上只会出现另一个命令行提示符。manpage中说,当以sh调用bash时,bash只会执行最简化的启动步骤,不读入任何配置文件。
2.输入:
logout
屏幕出现 bash: logout: not login shell: use `exit' ,说明我们当前的shell不是一个登录shell;
3.输入:
exit
屏幕显示exit,然后回到最初的登录shell
由于我们用sh命令启动的shell不是登录shell,所以它退出时不会执行.bash_logout
4.输入:
sh --login
屏幕显示hello from .profile。看看manpage,--login选项用来启动一个登录shell,此时用sh调用bash,它将会执行/etc/profile以及 ~/.profile,这正是我们得到的结果。
5.输入:
logout
屏幕显示 hello from .bash_logout
由于我们退出的是一个登录shell,所以执行了.bash_logout
实验三:
1.输入:
bash
屏幕显示 hello from .bashrc。因为当前用bash命令启动的不是登录shell,所以执行了.bashrc
2.输入:
logout
屏幕出现 bash: logout: not login shell: use `exit' ,说明我们当前的shell不是一个登录shell;
3.输入:
exit
屏幕显示exit,然后回到最初的登录shell
由于不是登录shell,所以它退出时不执行.bash_logout
4.输入:
bash --login
屏幕显示hello from .bash_profile。--login选项用来启动一个登录shell,此时bash的表现与实验一相同。
5.输入:
logout
屏幕显示 hello from .bash_logout
由于我们退出的是一个登录shell,所以执行了.bash_logout
小结:以上的简单实验直观地显示了bash在何种情况下将执行哪个配置文件,但实际上bash的行为还受到启动选项和一些环境变量的影响,情况将会很复杂。若需要深入研究请认真研读manpage。
其实就是 login shell 和 非 login shell 的区别,bash 手册里写的很清楚。
不过上面的工作还是很好的,辛苦了,呵呵。
多读读文档很多时候事半功倍。 |
|