<imghch AT gmail DOT com>
shell 程序 /bin/bash
(以下以 "shell" 称呼) 使用了一个启动文件集合,来帮助创造一个运行的环境。每一个文件都有特殊的功用并对登录和交互环境有不同的影响,有的文件还能使登入与交互环境有所不同。放在 /etc 目录下的一些文件提供了全局设置。如果相类似的设置文件出现在某个用户起始文件夹下 (~/),那么在登入该用户时,它将替代该全局设置。
shell 启动脚本主要有以下几个
/etc/profile
/etc/bashrc
~/.bash_profile
~/.bashrc
~/.bash_logout
它们用来设置单用户的启动环境,也可以实现开机单用户的程序,但要明确他们都是属于 bash 范畴而不是系统范畴。
它们的具体作用介绍如下
/etc/profile, ~/.bash_profile
是在启动一个交互登录 shell 的时候被调用。一个交互的登录 shell 会在 /bin/login
成功登录之后运行。
/etc/bashrc, ~/.bashrc
是在一个交互的非登录 shell 启动的时候被调用。一个交互的非登录 shell 是通过命令行来运行的,如$/bin/bash。一般一个非交互的 shell 出现在运行 shell 脚本的时候。之所以叫非交互的 shell,是因为它不在命令行上等待输入而只是执行脚本程序。
~/.bash_logout
在用户注销登录的时候被读取
这些 shell 脚本按以下顺序执行
/etc/profile
---> /etc/profile.d/*.sh
~/.bash_profile
---> ~/.bashrc
---> /etc/bashrc
典型场景
在每一个 shell 启动文件中加入 echo "[ filename ] is running."
(如在 /etc/profile
中添加 echo "[ /etc/profile ] is running."
)可以清楚地观察结果.
user login (interactive, login)
Using username "root". Authenticating with public key "rsa-key-20090720" Last login: Fri Sep 4 01:28:35 2009 from 192.168.101.1 [ /etc/profile ] is running. [ ~/.bash_profile ] is running. [ ~/.bashrc ] is running. [ /etc/bashrc ] is running. root0[ ~ ]#
bash --login
(interactive, login)
root0[ ~ ]# bash --login [ /etc/profile ] is running. [ ~/.bash_profile ] is running. [ ~/.bashrc ] is running. [ /etc/bashrc ] is running. root0[ ~ ]#
bash
(interactive, non-login)
root0[ ~ ]# bash [ ~/.bashrc ] is running. [ /etc/bashrc ] is running. root0[ ~ ]#
su --login
(interactive, login)
root2[ ~ ]# su --login [ /etc/profile ] is running. [ ~/.bash_profile ] is running. [ ~/.bashrc ] is running. [ /etc/bashrc ] is running. root0[ ~ ]#
su
(interactive, non-login)
root0[ ~ ]# su [ ~/.bashrc ] is running. [ /etc/bashrc ] is running. root0[ ~ ]#
非交互 bash - 既执行脚本 (non-interactive, non-login)
root0[ ~ ]# cat bash_test #!/bin/bash echo "bash test" root0[ ~ ]# ./bash_test bash test root0[ ~ ]#