现在的位置: 首页 > 综合 > 正文

Linux如何修改env看到的环境变量? .bashrc和.bash_profile区别

2013年08月01日 ⁄ 综合 ⁄ 共 1549字 ⁄ 字号 评论关闭

一、首先了解一下set、env、export的区别:
set 显示当前shell的变量,包括当前用户的变量
env 显示当前用户的变量
export 显示当前导出成用户变量的shell变量

每个shell有自己特有的变量(set)显示的变量,这个和用户变量是不同的,当前用户变量和你用什么shell无关,不管你用什么shell都在,比如 HOME,,SHELL等这些变量,但shell自己的变量不同shell是不同的,比如BASH_ARGCBASH,这些变量只有set才会显示,是bash特有的,export不加参数的时候,显示哪些变量被导出成了用户变量,因为一个shell自己的变量可以通过export
导出变成一个用户变量。

如用户想增加一目录到PATH中,操作如下:
1.vim .bashrc增加sbin目录到PATH中
$export PATH=$PATH:/sbin 或者export PATH=/sbin:$PATH

2.source到环境变量中
$source

3.检验设置的PATH是否生效
set|grep PATH  或env|grep PATH  或 export|grep PATH

二、.bashrc和.bash_profile的区别

.bash_profile会用在login shell
.bashrc 使用在interactive non-login shell

Bash下每个用户都可以配置两个初始文件:.bash_profile和.bashrc,文件存储在~根目录中。man bash中的相关解释如下:

,----------------------------------------------------------------------------
| ~/.bash_profile
| The personal initialization file, executed for login shells
| ~/.bashrc
| The individual per-interactive-shell startup file
`----------------------------------------------------------------------------

* 每次bash作为login shell启动时会执行.bash_profile。

* 每次bash作为普通的交互shell(interactive shell)启动时会执行.bashrc

* 注意
1)在shell脚本中“#!/usr/bin/bash”启动的bash并不执行.bashrc。因为这里的bash不是interactive shell。

2)bash作为login shell(login bash)启动时并不执行.bashrc。虽然该shell也是interactive shell,但它不是普通的shell。

* 一般.bash_profile里都会调用.bashrc

尽管login bash启动时不会自动执行.bashrc,惯例上会在.bash_profile中显式调用.bashrc。所以在你的.bash_profile文件中,很可能会看到如下的代码片段:

if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

.bashrc 使用在interactive non-login shell。意思是你每次运行一个bash脚本的话,.bashrc就会被执行一次。有个简单的方法,你在.bash_profile和.bashrc里都用echo打印点东西。,就可以看到着两个文件都是什么时候被执行的了。

编辑/etc/profile修改全局环境变量
编辑.bash_profile修改当前用户的环境变量
修改完成之后source一下即可生效,例如source ~/.bash_profile

抱歉!评论已关闭.