bash 的配置文件加載順序


bash配置文件的加載順序和登陸方式有關,下面先介紹下登陸方式。

1 登陸方式有2種

  登陸式SHELL:

  •     su - oracle 
  •       su -l oracle
  •     正常從終端登陸

  非登錄式SHELL:

  •     su oracle
  •     圖形終端打開命令窗口
  •     自動執行的shell腳本

2 bash配置文件的分兩大類

  • 全局配置:/etc/profile,   /etc/profile.d/*.sh,   /etc/bashrc 
  • 個人配置:~/.bash_profile,    ~/.bashrc

profile類文件作用

  •   定義環境變量
  •   運行命令或者腳本

bashrc類文件作用

  •   定義本地變量,函數
  •   命令別名

3 加載順序

登陸式SHELLL配置文件加載順序:/etc/profile > .bash_profile > .bash_login > .profile > .bash_logout.

非登錄式SHELL配置文件加載順序:/etc/bash.bashrc > .bashrc

注: 先加載的配置文件的配置,可能會被后加載的配置所覆蓋

下面一張圖展示下加載順序, A >B1>B2>B2>C

4 主要代碼分析

4.1 在/etc/profile文件中, 我們可以看到如下代碼

for i in /etc/profile.d/*.sh ; do
    if [ -r "$i" ]; then
        if [ "${-#*i}" != "$-" ]; then
            . "$i"
        else
            . "$i" >/dev/null 2>&1
        fi
    fi
done

簡單的說,我們的/etc/profile這個文件進行一系列的設置后, 最后需要遍歷下/etc/profile.d這個目錄下的所有sh文件, 然后source每個文件,讓每個文件的設置生效。

4.2 在~/.bash_profile文件中,我們可以看到如下代碼

 

[root@centos6 ~]# cat ~/.bash_profile 
# .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

我們可以看出來,在~/.bash_profile文件中, 判斷了~/.bashrc文件是不是存在,如果存在,也source下,讓其生效。

4.3 在~/.bashrc文件中,我們可以看到如下代碼

[root@centos6 ~]# cat ~/.bashrc
# .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

我們可以看出來,先設置了一些自定義的別名設置,然后去source了/etc/bashrc這個文件。

4.4 在/etc/bashrc文件中, 我們可以看到如下代碼

if ! shopt -q login_shell ; then # We're not a login shell
    # Need to redefine pathmunge, it get's undefined at the end of /etc/profile
    pathmunge () {
        case ":${PATH}:" in
            *:"$1":*)
                ;;
            *)
                if [ "$2" = "after" ] ; then
                    PATH=$PATH:$1
                else
                    PATH=$1:$PATH
                fi
        esac
    }

    # By default, we want umask to get set. This sets it for non-login shell.
    # Current threshold for system reserved uid/gids is 200
    # You could check uidgid reservation validity in
    # /usr/share/doc/setup-*/uidgid file
    if [ $UID -gt 199 ] && [ "`/usr/bin/id -gn`" = "`/usr/bin/id -un`" ]; then
       umask 002
    else
       umask 022
    fi

    # Only display echos from profile.d scripts if we are no login shell
    # and interactive - otherwise just process them to set envvars
    for i in /etc/profile.d/*.sh; do
        if [ -r "$i" ]; then
            if [ "$PS1" ]; then
                . "$i"
            else
                . "$i" >/dev/null 2>&1
            fi
        fi
    done

    unset i
    unset pathmunge
fi

我們可以看到,最后一部分代碼表示在非登錄shell中, /etc/bashrc文件會source /etc/prifile.d目錄下的所有sh文件。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM