Linux 之 /etc/profile、~/.bash_profile 等幾個檔案的執行過程

來源:互聯網
上載者:User

在登入Linux時要執行檔案的過程如下:
在剛登入Linux時,首先啟動 /etc/profile 檔案,然後再啟動使用者目錄下的 ~/.bash_profile、 ~/.bash_login或 ~/.profile檔案中的其中一個,

執行的順序為:~/.bash_profile、 ~/.bash_login、 ~/.profile。

如果 ~/.bash_profile檔案存在的話,一般還會執行 ~/.bashrc檔案。

因為在 ~/.bash_profile檔案中一般會有下面的代碼:
if [ -f ~/.bashrc ] ; then
   . ./bashrc
fi

~/.bashrc中,一般還會有以下代碼:
if [ -f /etc/bashrc ] ; then
   . /bashrc
fi

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

執行順序為: /etc/profile -> (~/.bash_profile | ~/.bash_login | ~/.profile) -> ~/.bashrc -> /etc/bashrc -> ~/.bash_logout

關於各個檔案的範圍,在網上找到了以下說明:

(1) /etc/profile: 此檔案為系統的每個使用者佈建環境資訊,當使用者第一次登入時,該檔案被執行. 並從/etc/profile.d目錄的設定檔中搜集shell的設定。

(2) /etc/bashrc: 為每一個運行bash shell的使用者執行此檔案.當bash shell被開啟時,該檔案被讀取(即每次新開一個終端,都會執行bashrc)。

(3) ~/.bash_profile: 每個使用者都可使用該檔案輸入專用於自己使用的shell資訊,當使用者登入時,該檔案僅僅執行一次。預設情況下,設定一些環境變數,執行使用者的.bashrc檔案。

(4) ~/.bashrc: 該檔案包含專用於你的bash shell的bash資訊,當登入時以及每次開啟新的shell時,該該檔案被讀取。

(5) ~/.bash_logout: 當每次退出系統(退出bash shell)時,執行該檔案. 另外,/etc/profile中設定的變數(全域)的可以作用於任何使用者,而~/.bashrc等中設定的變數(局部)只能繼承 /etc/profile中的變數,他們是"父子"關係。

(6) ~/.bash_profile: 是互動式、login 方式進入 bash 啟動並執行~/.bashrc 是互動式 non-login 方式進入 bash 啟動並執行通常二者設定大致相同,所以通常前者會調用後者。

/etc/profile和/etc/environment等各種環境變數設定檔案的用處

先將export LANG=zh_CN加入/etc/profile ,退出系統重新登入,登入提示顯示英文。

將/etc/profile 中的export LANG=zh_CN刪除,將LNAG=zh_CN加入/etc/environment,退出系統重新登入,登入提示顯示中文。

使用者環境建立的過程中總是先執行/etc/profile然後在讀取/etc/environment。為什麼會有如上所敘的不同呢?

應該是先執行/etc/environment,後執行/etc/profile。

/etc/environment是設定整個系統的環境,而/etc/profile是設定所有使用者的環境,前者與登入使用者無關,後者與登入使用者有關。

系統應用程式的執行與使用者環境可以是無關的,但與系統內容是相關的,所以當你登入時,你看到的提示資訊,象日期、時間資訊的顯示格式與系統內容的LANG是相關的,預設LANG=en_US,如果系統內容LANG=zh_CN,則提示資訊是中文的,否則是英文的。

對於使用者的SHELL初始化而言是先執行/etc/profile,再讀取檔案/etc/environment.對整個系統而言是先執行/etc/environment。這樣理解正確嗎?

/etc/enviroment --> /etc/profile --> $HOME/.profile -->$HOME/.env (如果存在)
/etc/profile 是所有使用者的環境變數
/etc/enviroment是系統的環境變數

登陸系統時shell讀取的順序應該是
/etc/profile ->/etc/enviroment -->$HOME/.profile -->$HOME/.env
原因應該是jtw所說的使用者環境和系統內容的區別了

如果同一個變數在使用者環境(/etc/profile)和系統內容(/etc/environment)有不同的值那應該是以使用者環境為準了。

 

轉載聲明: 本文轉自 http://blog.csdn.net/dingxy/archive/2009/03/23/4016383.aspx

 

===============================================================

 

拓展參考:

linux環境變數

bash again shell的開機檔案

Ubuntu 之 adb 環境變數配置

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.