linux环境变量的加载顺序

当使用export设置环境变量的时候,注意前面的环境变量会覆盖后面设置的环境变量。
例如:

1
2
export JAVA_HOME/usr/java1.7
export PATH=$PATH:$JAVA_HOME/bin

当在/etc/profile中设置这2个选项的时候,如果PATH中已经包含了java的运行时环境,那么此设置会失败。

要想使自定义设置生效,最好将自定义的path设置在前面,如下:

1
2
export JAVA_HOME/usr/java1.7
export PATH=$JAVA_HOME/bin:$PATH

附:linux系统文件的执行顺序

在刚登录Linux时,首先启动 /etc/profile 文件,然后再启动用户目录下的 ~/.bash_profile、 ~/.bash_login或 ~/.profile文件中的其中一个,执行的顺序为:~/.bash_profile、 ~/.bash_login、 ~/.profile。如果 ~/.bash_profile文件存在的话,一般还会执行 ~/.bashrc文件。因为在 ~/.bash_profile文件中一般会有下面的代码:

if [ -f ~/.bashrc ] ; then 

. ./bashrc 

fi 

~/.bashrc中,一般还会有以下代码: 

if [ -f /etc/bashrc ] ; then 

. /bashrc 

fi 

所以,~/.bashrc会调用 /etc/bashrc文件。最后,在退出shell时,还会执行 ~/.bash_logout文件。

执行顺序为:/etc/profile -> (~/.bash_profile | ~/.bash_login | ~/.profile) -> ~/.bashrc -> /etc/bashrc -> ~/.bash_logout