Linux的环境配置文件包括/etc/profile
、~/bash_profile
、~/.bashrc
等,它们通常会在用户登录时被执行。这些配置文件是每次登录都会调用吗?为什么有时候/etc/profile
没有生效?它们的执行顺序是怎么样的?
跟小编一起来看看吧~
注:本文基于Bash,其它shell可能不适用。
调用逻辑和顺序
如果你不知道login shell和交互式shell是什么意思,别急,文章后面会介绍。
先说结论:
- 如果一个shell是login shell,
/etc/profile
会被调用,随后按顺序查找~/.bash_profile
,~/.bash_login
, 和~/.profile
,并执行最先找到的一个。 - 如果是交互式的non-login shell,则会调用
~/.bashrc
。 - 如果是非交互式的non-login shell,则会执行环境变量
$BASH_ENV
中的脚本(如果存在)。
一些特殊情况:
上面这些被调用的脚本可能去调用其它脚本。例如
/etc/profile
可能去调用/etc/profile.d/
目录中的脚本;在Centos中,~/.bash_profile
会调用~/.bashrc
, 如下:1
2
3
4
5
6
7[mao@VM_0_14_centos ~]$ cat ~/.bash_profile
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi启动shell时可以使用
--noprofile
、--norc
等选项使shell不去调用对应的配置文件,或者指定调用的配置文件,很少用到,不展开讨论。如果启动shell时使用
sh
命令(sh
是/bin/bash
的一个软链接),情况又不同,如下:使用
.
或者source
去执行一个脚本,是在当前shell中执行脚本,不会启动新的shell,所以不会去加载任何配置文件,没有上面这些流程。
什么是login shell?
简而言之:
- 一般来说,启动shell时需要认证(密码、公钥等方式)的shell是login shell,比如登录云服务器。
- 被其它进程直接启动的shell一般是non-login shell,比如直接执行
bash
命令。 - 启动shell时带上
--login
参数的是login shell,比如直接执行命令bash --login
。
具体定义和判断方法,参考:什么是Login Shell和Non-Loin Shell?
什么是交互式shell?
shell按照是否需要交互可以分为交互式shell:interactive shell
和非交互式shell:non-interactive shell
。
交互式shell:
- 你可以在终端中输入命令并执行,且启动shell时无
-c
选项; - 或者启动shell时有
-i
参数,可以指定这个shell为交互式shell。
非交互式shell:
- 系统启动脚本、后台脚本等不需要交互的shell;
- 启动时有
-c
选项的shell。
详细定义和测试方法参考:什么是交互式shell和非交互式shell?