1. 程式人生 > 其它 >Linux系統配置檔案詳解

Linux系統配置檔案詳解


區別


首先先總體看一下區別

============
/etc/profile

此檔案為系統的每個使用者設定環境資訊,對所有使用者有效

===========
/etc/bashrc (ubuntu為 /etc/bash.bashrc)

為每一個執行bash shell的使用者執行此檔案.對所有使用者有效

===============
~/.bash_profile (ubuntu為 ~/.profile)

類似/etc/profile,但僅僅針對當前使用者有效

=========
~/.bashrc

類似/etc/bashrc,但僅僅針對當前使用者有效

==============
~/.bash_logout

當每次退出系統(退出bash shell)時,執行該檔案. 
  • Linux的Shell種類眾多,常見的有:
    Bourne Shell(/usr/bin/sh或/bin/sh)、
    Bourne Again Shell(/bin/bash)、
    C Shell(/usr/bin/csh)、
    K Shell(/usr/bin/ksh)、
    Shell for Root(/sbin/sh)等等。
  • 不同的Shell語言的語法有所不同,所以不能交換使用。每種Shell都有其特色之處,基本上,掌握其中任何一種 就足夠了。在本文中,我們關注的重點是Bash,也就是Bourne Again Shell,由於易用和免費,Bash在日常工作中被廣泛使用;同時,Bash也是大多數Linux系統預設的Shell。

login和non login


loginnon login指的是用登入或非登入的方式開啟bash shell,不同的方式的讀取的配置檔案不同,可以歸納為下表:

login non login
全域性 /etc/profile /etc/bashrc
單使用者 ~/.bash_profile ~/.bashrc

執行順序


登入Linux時執行

在 剛登入Linux時,首先啟動 /etc/profile 檔案,然後再啟動使用者目錄下的 ~/.bash_profile

再執行使用者的bash設定

如果 ~/.bash_profile檔案存在的話,會執行使用者的 ~/.bashrc

檔案。

#if running bash

if [ -n "$BASH_VERSION" ]; then

	# include .bashrc if it exists

    if [ -f "$HOME/.bashrc" ]; then
    	. "$HOME/.bashrc"
    fi
fi

同樣~/.bashrc中,一般還會在檔案的前面有以下程式碼,來執行/etc/bashrc

if [ -f /etc/bashrc ] ; then
 . /etc/bashrc

所以,~/.bashrc會呼叫 /etc/bashrc檔案。最後,在退出shell時,還會執行 ~/.bash_logout檔案。

執行順序為:

  • /etc/profile
  • ~/.bash_profile | ~/.bash_login | ~/.profile
  • ~/.bashrc
  • /etc/bashrc
  • ~/.bash_logout

區別和聯絡


  • 在 /etc目錄是系統級(全域性)的配置檔案,當在使用者主目錄下找不到~/.bash_profile 和~/.bashrc時,就會讀取這兩個檔案。
  • /etc/profile 中設定的變數(全域性)的可以作用於任何使用者,而 ~/.bashrc 中設定的變數(區域性)只能繼承 /etc/profile 中的變數,他們是“父子”關係。
  • ~/.bash_profile 是互動式、login 方式進入 bash 執行的; ~/.bashrc 是互動式 non-login 方式進入 bash 執行的。通常二者設定大致相同,所以通常前者會呼叫後者。設定生效:可以重啟生效,也可以使用命令:source。
  • ~/.bash_history是bash shell的歷史記錄檔案,裡面記錄了你在bash shell中輸入的所有命令。可通過HISSIZE環境變數設定在歷史記錄檔案裡儲存記錄的條數。

其他


下面是幾個例子:

  1. 圖形模式登入時,順序讀取:/etc/profile~/.profile
  2. 圖形模式登入後,開啟終端時,順序讀取:/etc/bash.bashrc~/.bashrc
  3. 文字模式登入時,順序讀取:/etc/bash.bashrc/etc/profile~/.bash_profile
  4. 從其它使用者su到該使用者,則分兩種情況:
    (1)如果帶-l引數(或-引數,–login引數),如:su -l username,則bash是lonin的,它將順序讀取以下配置檔案:/etc/bash.bashrc/etc/profile~ /.bash_profile
    (2)如果沒有帶-l引數,則bash是non-login的,它將順序讀取:/etc/bash.bashrc~/.bashrc
  5. 登出時,或退出su登入的使用者,如果是longin方式,那麼bash會讀取:~/.bash_logout
  6. 執行自定義的shell檔案時,若使用“bash -l a.sh”的方式,則bash會讀取行:/etc/profile~/.bash_profile,若使用其它方式,如:bash a.sh, ./a.sh,sh a.sh(這個不屬於bash shell),則不會讀取上面的任何檔案。


參考:linux下的/etc/profile、/etc/bashrc、/.bash_profile、/.bashrc檔案