linux下设定环境变量的方法介绍

那么需要将export命令写入某个系统文件中,拥有这种功能的文件常见的有如下几个:
/etc/environment 或 /etc/profile 或 ~/.profile 或 /etc/bash.bashrc 或 ~/.bashrc等。
有这么多可以用,到底它们有什么区别,谁先谁后呢?
首先,来看看这几个文件都是干什么的:
1./etc/environment–>是系统在登录时读取的第一个文件,用于为所有进程设置环境变量。系统使用此文件时并不是执行此文件中的命 令,而是根据KEY=VALUE模式的代码,对KEY赋值以VALUE,因此文件中如果要定义PATH环境变量,只需加入一行形如 PATH=$PATH:/xxx/bin的代码即可。
2./etc/profile–>是系统登录时执行的第二个文件,可以用于设定针对全系统所有用户的环境变量。
3.~/.profile–>是对应当前登录用户的profile文件,用于定制当前用户的个人工作环境。
4./etc/bash.bashrc–>是针对所有用户的bash初始化文件,在此中设定的环境变量将应用于所有用户的shell中,此文件会在用户每次打开shell时执行一次。
5.~/.bashrc–>是对应当前登录用户的bash初始化文件,当用户每次打开shell时,系统都会执行此文件一次。
那么根据以上描述,这几个文件的执行先后顺序应当是:
/etc/enviroment –>/etc/profile –>~/.profile –>/etc/bash.bashrc–> ~/.bashrc
为了验证此顺序是否正确,这里可以做一个小试验,假定我们登录的用户名为xyz。在/etc/environment中加入一行:
ENV_MSG=”this is /etc/environment”
这样也就是添加了一个环境变量ENV_MSG,然后在/etc/profile中加入两行代码:
echo $ENV_MSG >> /home/xyz/log.txt
echo “this is /etc/profile” >> /home/xyz/log.txt
这样,如果/etc/environment在profile之前被系统读取,则在/home/xyz/log.txt 中会先后打印出EVN_MSG的值和 this is /etc/profile这两条消息。
在/home/xyz/.profile中加入一行代码:
echo “this is .profile” >> /home/xyz/log.txt
在/etc/bash.bashrc中加入一行代码:
echo “this is /etc/bash.bashrc” >> /home/xyz/log.txt
在/home/xyz/.bashrc中加入一行代码:
echo “this is .bashrc” >> /home/xyz/log.txt
然后,重启计算机,看看log.txt文件中会是什么样子。
启动计算机后以xyz用户登录并立即打开/home/xyz/log.txt,可以看到文件中有如下三行消息:
this is /etc/environment
this is /etc/profile
this is .profile
这说明系统在启动登录的过程中依次读取执行了/etc/enviroment 、/etc/profile和~/.profile中的内容。
然后打开一个shell窗口,log文件中就会增加两行消息:
this is /etc/bash.bashrc
this is .bashrc
这说明在打开shell过程中,系统又依次执行/etc/bash.bashrc和~/.bashrc。如果关闭shell窗口后再次打开一个新的 shell窗口,则log文件中会又增加两行同样的消息。由此可以获知,每次打开一个新shell,系统都会重复执行这两个文件,而不会再动那头三个文件 的内容。
接下来我们再打开/etc/environment ,把刚才写入的那行改成ENV_MSG=”this is not /etc/environment”,然后注销,重新以xyz登录,结果会发现log文件中会又多了三行:
this is not /etc/environment
this is /etc/profile
this is .profile
这也就看出来,注销重登录也会引发系统对这三个文件的读取与执行。
不过,如果按下Ctrl+Alt+F1,然后登录xyz,那么log文件中会多出来如下几行,这又是怎么回事呢?
this is /etc/bash.bashrc
this is /etc/environment
this is /etc/profile
this is .bashrc
this is .profile

(0)

相关推荐