参考资料:http://blog.chinaunix.net/uid-14735472-id-3190130.html
登录Linux时,首先启动/etc/profile 文件,然后再启动用户目录下的 ~/.bash_profile、 ~/.bash_login或 ~/.profile文件中的其中一个,执行的顺序为:~/.bash_profile、 ~/.bash_login、 ~/.profile。如果~/.bash_profile文件存在的话,一般还会执行 ~/.bashrc文件。因为在 ~/.bash_profile文件中一般会有下面的代码:
# .bash_profile
# Get the aliases and functions 获取别名和函数
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
...
而~/.bashrc文件一般会有以下代码:
# .bashrc
# User specific aliases and functions
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
也就是,~/.bashrc会调用 /etc/bashrc文件。
最后,在退出shell时,还会执行 ~/.bash_logout文件。
综上执行顺序为:/etc/profile ----> (~/.bash_profile | ~/.bash_login | ~/.profile) ----> ~/.bashrc ---->/etc/bashrc ----> ~/.bash_logout。
1、/etc/profile:为系统的每个用户设置环境信息,当用户第一次登录时,该文件被执行.并从/etc/profile.d目录的配置文件中搜集shell的设置。英文描述:
# /etc/profile
# System wide environment and startup programs, for login setup
# Functions and aliases go in /etc/bashrc
翻译:系统通用(全系统)的环境和启动程序,登录设置功能和别名请编辑/etc/bashrc
# It's NOT a good idea to change this file unless you know what you
# are doing. It's much better to create a custom.sh shell script in
# /etc/profile.d/ to make custom changes to your environment, as this
# will prevent the need for merging in future updates.
翻译:不建议更改此文件,最好在/etc/profile.d/中创建一个以.sh结尾的shell脚本
文件,用于对您的环境进行自定义更改,防止在将来的更新中合并的需要。
如果你对/etc/profile有修改的话必须重启或使用source /etc/profile,你的修改才会生效,此修改对每个用户都生效。
2、~/.bash_profile:作用:获取别名和函数。每个用户都可使用该文件输入专用于自己使用的shell信息,当用户登录时,该文件仅仅执行一次,默认情况下,他设置一些环境变量,执行用户的.bashrc文件。
此文件类似于/etc/profile,也是需要需要重启才会生效,/etc/profile对所有用户生效,~/.bash_profile只对当前用户生效。
3、/etc/bashrc:为每一个运行bash shell的用户执行此文件.当bash shell被打开时,该文件被读取。英文描述为:
# /etc/bashrc
# System wide functions and aliases
# Environment stuff goes in /etc/profile
翻译:全系统的函数和别名环境配置进入/etc/profile
# It's NOT a good idea to change this file unless you know what you
# are doing. It's much better to create a custom.sh shell script in
# /etc/profile.d/ to make custom changes to your environment, as this
# will prevent the need for merging in future updates.
如果你对该文件有修改的话不用重启,重新打开一个bash即可生效,此修改对每个用户都生效,并在以后打开的bash都生效。
4、~/.bashrc:用户特定别名和功能。该文件包含专用于你的bash shell的bash信息,当登录时以及每次打开新的shell时,该文件被读取.(每个用户都有一个.bashrc文件,在用户目录下)
此文件类似于/etc/bashrc,不需要重启生效,重新打开一个bash即可生效, /etc/bashrc对所有用户新打开的bash都生效,但~/.bashrc只对当前用户新打开的bash生效。
5、~/.bash_logout:当每次退出系统(退出bash shell)时,执行该文件。
附加:
/etc/profile中设定的变量(全局)的可以作用于任何用户,而~/.bashrc等中设定的变量(局部)只能继承/etc/profile中的变量,他们是"父子"关系。
~/.bash_profile 是交互式、login 方式进入bash 运行的;
~/.bashrc 是交互式、non-login 方式进入bash 运行的;
通常二者设置大致相同,所以通常前者会调用后者。
在/etc/profile,/etc/bashrc,~/.bashrc和~/.bash_profile文件的最后追加同一个变量分别赋予不同的值,结果表明变量最后的值为~/.bash_profile里的值。(4个文件都没有修改其他设置,都是安装系统后的默认值。)
再有就是4个文件都追加一个值到同一个文件,开机后查看该文件内容的顺序为:
/etc/profile
~/.bash_profile
~/.bashrc
/etc/bashrc