linux下设定环境变量的方法

详细出处参考:http://www.jb51.net/LINUXjishu/64734.html

在linux下设定环境变量时,如果只是临时用一下,可以直接在shell下用set或export命令设定环境变量,如果希望此环境变量每次开机或打开 shell时自动设定而无须每次都手动设定.
那么需要将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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值