在一般的 linux 或者 unix 系统中, 都可以通过编辑 bashrc 和 profile 来设置用户的工作环境, 很多文章对于 profile 和 bashrc 也都有使用, 但究竟每个文件都有什么作用和该如何使用呢? 首先我们
在一般的 linux 或者 unix 系统中, 都可以通过编辑 bashrc 和 profile来设置用户的工作环境, 很多文章对于 profile 和 bashrc 也都有使用, 但究竟每个文件都有什么作用和该如何使用呢? 首先我们来看系统中的这些文件, 一般的系统可能会有 /etc/profile/etc/bashrc~/.bashrc~/.profile 而如果系统是 ubuntu 或者 debian 的话, 就不会有 /etc/bashrc 而会有 /etc/bash.bashrc 文件. Shell 的模式 login shell 和 no-login shell interactive shell 和 non-interactive shell 在可能存在的模式组合中 RC 文件的执行 /etc/profile~/.profile
/etc/bash.bashrc~/.bashrc 通过 bash -c “CMD” 或者 bash BASHFILE 命令执行的 shell 这些命令什么都不会执行, 也就是设置 PS1 变量, 不执行任何 RC 文件 这是最特殊的一种模式, 理论上应该既是 非交互 也是 非登入的, 但是实际上他不会设置 PS1, 但是还会执行 bashrc 和 profile 的区别 profile bashrc 普通 login shell /etc/profile => /etc/bash.bashrc~/.profile => ~/.bashrc => /etc/bashrc
/etc/bash.bashrc~/.bashrc => /etc/bashrc
ssh server “CMD” /etc/bash.bashrc => /etc/profile~/.bashrc => | /etc/bashrc => /etc/profile | ~/.profile 这里会有点小混乱, 因为既有 /etc/bash.bashrc 又有 /etc/bashrc, 其实是这样的 ubuntu 和 debian 有 /etc/bash.bashrc 文件但是没有 /etc/bashrc, 其他的系统基本都是只有 /etc/bashrc 没有 /etc/bash.bashrc. 最终修改 export system_profile_loaded=1 这样其他文件就可以根据 $system_profile_loaded 来判断是否已经载入过 profile, 接着我们可以看到 unset ifiif [ "$PS1" ]; then if [ "$BASH" ]; then PS1='u@h:w$ ' if [ -f /etc/bash.bashrc ]; then . /etc/bash.bashrc fi else if [ "`id -u`" -eq 0 ]; then PS1='# ' else PS1='$ ' fi fifiumask 022 按照我们刚才的方案, 应该是不管任何情况都应该在文件末尾去载入 bashrc, 所以我们修改成 unset ifiumask 022if [ "$BASH" ]; then if [ "$PS1" ]; then PS1='u@h:w$ ' fi if [ -f /etc/bash.bashrc ]; then . /etc/bash.bashrc fielse if [ "`id -u`" -eq 0 ]; then PS1='# ' else PS1='$ ' fifi 当然也可以有其他该法,只要符合在文件末尾载入 bashrc 就可以了. [ -n "${system_bashrc_running}" ] && returnsystem_bashrc_running=1[ -z "${system_profile_loaded}" ] && source /etc/profile unset system_bashrc_running system_bashrc_runned=1 其中 system_bashrc_running 这样的变量都是为了防止2次反复调用而加入的. # ~/.profile: executed by Bourne-compatible login shells.if [ -n "$BASH" ]; then if [ -f ~/.bashrc ]; then . ~/.bashrc fifimesg n 而按照上述的修改规则只需要替换成 export local_profile_loaded=1if [ -n "$BASH" ]; then if [ -f ~/.bashrc ]; then . ~/.bashrc fifi 这样就始终再载入完 profile 以后去载入 bashrc 了, 接着我们像编辑 /etc/bash.bashrc 一样的去修改 ~/.bashrc, 文件头上加入 [ -n "${local_bashrc_running}" ] && returnlocal_bashrc_running=1[ -r /etc/bashrc -a -z "${system_bashrc_runned}" ] && source /etc/bashrc[ -r ~/.profile -a -z "${local_profile_loaded}" ] && source ~/.profile unset local_bashrc_running 用来防止反复加载 profile, 并且这里需要特殊注明的是 [ -r /etc/bashrc -a -z "${system_bashrc_runned}" ] && source /etc/bashrc /etc/bashrc 这个文件只有在 mac 之类的系统下才有, 所以 ubuntu 这里这行可以不加, 不过有判断是否存在所以加了也没关系. |
本文始发于微信公众号(飓风网络安全):/etc/bashrc和/etc/profile区别
- 左青龙
- 微信扫一扫
-
- 右白虎
- 微信扫一扫
-
评论