bashrc,bash_profile等shell配置文件详解

一、bashrc,bash_profile等文件执行顺序

如何确定这些文件的执行顺序呢? 最好的方法就是在这些文件的开头添加一个输出语句,这样文件一执行马上就会输出内容。

我们首先在/etc/profile,/etc/bashrc,~/.bash_profile,~/.bashrc,~/.bash_logout文件开头添加以下行:

1
echo "I am `pwd`/`basename $0` ,executed at `date`."

命令执行时会输出文件名和执行时间到/tmp/bashseq这个文件。

为什么不添加到文件尾部?因为这些文件可以执行,在执行过程中会调用其它文件,如果以上语句添加到文件尾部,则可能被调用的文件好像在前面执行,这就会发生错误。

修改/tmp/bashseq文件权限, 使所有用户可写:

1
chmod 666 /tmp/bashseq

重启一次,查看/tmp/bashseq文件,内容如下:

1
2
3
4
I am /etc/profile ,exectued at Wed May 11 10:23:18 CST 2011.
I am ~/.bash_profile ,exectued at Wed May 11 10:23:19 CST 2011.
I am ~/.bashrc ,exectued at Wed May 11 10:23:19 CST 2011.
I am /etc/bashrc ,exectued at Wed May 11 10:23:19 CST 2011.

执行顺序为: /etc/profile -> ~/.bash_profile -> ~/.bashrc -> /etc/bashrc

如下图所示:

bashrc,bash_profile

将当前用户logout,重新login, 再查看/tmp/bashseq文件,内容如下:

1
2
3
4
5
I am ~/.bash_logout ,executed at Wed May 11 10:24:03 CST 2011.
I am /etc/profile ,exectued at Wed May 11 10:25:50 CST 2011.
I am ~/.bash_profile ,exectued at Wed May 11 10:25:50 CST 2011.
I am ~/.bashrc ,exectued at Wed May 11 10:25:50 CST 2011.
I am /etc/bashrc ,exectued at Wed May 11 10:25:50 CST 2011.

多了一个~/.bash_logout,可见用户logout只执行~/.bash_logout,每次登录都会按照 /etc/profile -> ~/.bash_profile -> ~/.bashrc -> /etc/bashrc的顺序执行这四个shell配置文件。

二、各个文件作用

清空/tmp/bashseq文件, 使用普通用户登录, 查看/tmp/bashseq文件,内容如下:

1
2
I am /etc/profile ,exectued at Wed May 11 10:24:12 CST 2011.
I am /etc/bashrc ,exectued at Wed May 11 10:24:12 CST 2011.

注意此处没有~/.bash_profile和 ~/.bashrc的记录,这是因为普通用户目录下没有这两个文件。

由此可见,上面四个文件/etc/profile,/etc/bashrc,~/.bash_profile,~/.bashrc中:

  • 前两件是全局的,每一个用户登录都会执行
  • 后两个是专用的,针对特定用户设定.

再来看看~/.bash_profile,~/.bashrc这两个文件

  • .bash_profile内容:
1
2
3
4
5
6
7
8
9
# .bash_profile
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME /bin
export PATH
unset USERNAME

.bash_profile作用设置自定义的环境和开机启动程序

  • .bashrc内容:
1
2
3
4
5
6
7
8
9
10
# .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
##end

.bashrc作用:设置自定义别名和函数。

三、总结

讲到这里,你应该知道了如何对bashrc,bash_profile,bash_profile进行解析了。这些文件的界限并非十分明确,但是用户和全局必须分清。掌握这些内容,有助于编写shell script,也有助于对系统进行配置。

四、参考文章

转载自:http://www.jsxubar.info/bashrc-bash_profile.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值