在登入 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
. /etc/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 等各種環境變數設定檔案的用處
1)先將 export LANG=zh_CN 加入/etc/profile,退出系統重新登入,登入提示顯示英文。
2)先將/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
原因應該是使用者環境和系統環境的區別了,如果同一個變數在使用者環境 (/etc/profile) 和系統環境 (/etc/environment) 有不同的值,那應該是以使用者環境為準

原文連結:http://www.linuxde.net/2013/10/15352.html