Shell的启动方式
1、Shell四种启动方式
-
交互式的登录Shell
-
非交互式的登录Shell
-
交互式的非登录Shell
-
非交互式的非登录Shell
交互式是Shell等待你的输入,并在你输入的一个个命令能及时查看结果非交互式则是新进程运行命令或者Shell脚本,新进程的程序没法与你互动,无法等待你输入的命令
登录式是用账号和密码后使用Shell
非登录式是直接使用Shell
1.1 判断是否交互式$PS1
输出的值不为空,为交互式,否则为非交互式
#输出的值不为空,为交互式
[root@VM_0_6_centos ~]# echo $PS1
[\u@\h \W]\$
[root@VM_0_6_centos ~]# vim test.sh # 编写文件,输出$PS1变量
echo $PS1
[root@VM_0_6_centos ~]# . test.sh #等同于source test.sh
[\u@\h \W]\$
[root@VM_0_6_centos ~]# bash test.sh #输出的值是空值
1.2 判断是否登录式shopt login_shell
[root@VM_0_6_centos ~]# shopt login_shell #shopt命令用于显示和设置shell中的行为选项
login_shell on
[root@VM_0_6_centos ~]# vim test.sh #创建test.sh文件,判断是否登录式
shopt login_shell
[root@VM_0_6_centos ~]# . test.sh
login_shell on
[root@VM_0_6_centos ~]# vim test.sh #编写脚本文件
#! /bin/bash
#非交互式
echo $PS1
echo `shopt login_shell` # 反引号的字符串当作命令执行后替换原来的字符串
2、Shell配置文件加载
无论是否是交互式,是否是登录式,Bash Shell 在启动时总要配置其运行环境,例如初始化环境变量、设置命令提示符径等。这个过程是通过加载一系列配置文件完成的,这些配置文件其实就是 Shell 脚本文件。
-
2.1 Bash shell启动时相关的配置文件
如需深入了解,请打开文件阅读源码(C语言)
-
/etc/profile:系统全局环境变量设定,加载环境变量中的PATH、LOGNAME、MAIL等
-
~/.bash_profile: 用户家目录下的私有环境变量设定,加载环境变量PATH和~/.bashrc文件等
-
~/.bash_login:centos 7版本找不到
-
~/.profile:centos 7版本找不到
-
~/.bashrc:别名设置。
-
/etc/bashrc:系统全局环境变量设定,在~/.bashrc中加载
-
/etc/profile.d/*.sh
-
-
2.2 登入系统时候获得一个shell进程,读取设定档的步骤
/etc/profile,/etc/bashrc 是系统全局环境变量设定
~/.profile,~/.bashrc用户家目录下的私有环境变量设定/etc/profile → /etc/profile.d/*.sh → ~/.bash_profile → ~/.bashrc → [/etc/bashrc]
1、首先读入的是全局环境变量设定档/etc/profile,然后根据其内容读取额外的设定的文档,如
/etc/profile.d和/etc/inputrc
2、然后根据不同使用者帐号,去其家目录读取~/.bash_profile,如果这读取不了就读取~/.bash_login,这个也读取不了才会读取~/.profile,这三个文档设定基本上是一样的,读取有优先关系
3、然后在根据用户帐号读取~/.bashrc,至于~/.profile与~/.bashrc都具有个性化定制功能
~/.profile可以设定本用户专有的路径,环境变量,等,它只能登入的时候执行一次
~/.bashrc也是某用户专有设定文档,可以设定路径,命令别名,每个shell(当然也包括新开的子进程)启动时的执行都会使用它一次,间接的执行了/etc/bashrc -
2.3 登录式的Shell
文件加载顺序(从左到右):/etc/profile->~/.bash_profile->/etc/bashrc
-
2.4 非登录式的Shell
文件加载顺序(从左到右):~/.bash_profile->/etc/bashrc
3、修改Shell的配置文件
从上面可知,登录式和非登录式,都会加载~/.bash_profile。谨记每个用户加载的.bash_profile可能不一样,因为~符号代表当前用户的家目录
/etc/profile可以理解成window系统用户变量,~/.bash_profile是用户变量
在PATH变量中增加自定义命令的绝对路径
[test@VM_0_6_centos ~]# test #没有新增变量前的执行结果
bash: test.sh: command not found
[test@VM_0_6_centos ~]# vim test #在用户的家目录新增test文件
echo "自定义命令成功"
[test@VM_0_6_centos ~]$ chmod u+x .bashrc #给文件授权执行权限。为何新建文件还要授权,请去了解umask命令
[test@VM_0_6_centos ~]# vim .bashrc #在文件最好一行增加代码,/home/test就是用户的家目录
PATH=$PATH:/home/test
#重启SHELL
[test@VM_0_6_centos ~]$ mycommand #执行自定义命令
调用命令成功
参考C语言中文网Shell教程:http://c.biancheng.net/view/vip_3232.html