Linux進階之環境變量文件/etc/profile、/etc/bashrc、/etc/environment


一、Centos 環境變量/etc/profile/etc/profile.d

1、兩個文件都是設置環境變量的文件。

2、/etc/profile 是永久性的環境變量,是全局變量,/etc/profile.d/ 設置對所有用戶生效

3、/etc/profile.d/ 比 /etc/profile 好維護。不想要什么變量直接刪除/etc/profile.d/下對應的.sh 的shell腳本即可,不用像/etc/profile需要改動此文件。

區別:

/etc/profile 是文件

1、只有Login shell 啟動時才會運行 /etc/profile 這個腳本,而Non-login shell 不會調用這個腳本。

說明:當一個用戶登錄Linux系統或使用su -命令切換到另一個用戶時,也就是Login shell 啟動時,首先要確保執行的啟動腳本就是 /etc/profile 。

2、在/etc/profile 文件中設置的變量是全局變量。

/etc/profile.d 文件夾,下面包含很多.sh 腳本

1)在/etc/profile.d 目錄中存放的是一些應用程序所需的啟動腳本,而這些腳本文件是用來設置一些變量和運行一些初始化過程的。其中包括了顏色、語言、less、vim及which等命令的一些附加設置。

2)/etc/profile.d 下的腳本之所以能自動執行,是因為在/etc/profile 中有一個for循環語句來調用這些腳本。

環境變量配置

1、/etc/profile配置

#################################

#在文件最后添加

export PATH=/usr/local/tomcat/bin/:$PATH

##################################

2、/etc/profile.d配置

生成一個子配置文件tomcat.sh

###############################

export PATH=/usr/local/tomcat/bin/:$PATH

################################

二、/etc/profile/etc/bashrc的區別

/etc/profile:此文件為系統的每個用戶設置環境信息,當用戶第一次登錄時,該文件被執行,並從/etc/profile.d目錄的配置文件中搜集shell的設置。

/etc/bashrc:為每一個運行bash shell的用戶執行此文件,當bash shell被打開時,該文件被讀取。

~/.bash_profile:每個用戶都可使用該文件輸入專用於自己使用的shell信息,當用戶登錄時,該文件僅僅執行一次!默認情況下,他設置一些環境變量,執行用戶的.bashrc文件。是交互式login 方式進入 bash 運行的。

~/.bashrc:該文件包含專用於你的bash shell的bash信息,當登錄時以及每次打開新的shell時,該文件被讀取。交互式 non-login 方式進入 bash 運行的。

~/.bash_logout:當每次退出系統(退出bash shell)時,執行該文件。

另外,/etc/profile中設定的變量(全局)的可以作用於任何用戶,而~/.bashrc等中設定的變量(局部)只能繼承/etc/profile中的變量,他們是\"父子\"關系。通常二者設置大致相同,通常前者會調用后者

三、在登錄Linux時要執行文件的過程如下:

在剛登錄Linux時,首先啟動 /etc/profile 文件,然后再啟動用戶目錄下的 ~/.bash_profile、 ~/.bash_login或 ~/.profile文件中的其中一個(根據不同的linux操作系統的不同,命名不一樣)

執行的順序為:~/.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

四、/etc/profile/etc/environment等各種環境變量設置文件的用處

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

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

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

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

/etc/environment是設置整個系統的環境,而/etc/profile是設置所有用戶的環境,前者與登錄用戶無關,后者與登錄用戶有關。

系統應用程序的執行與用戶環境可無關但與系統環境是相關的,對於用戶的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)有不同的值那應該是以用戶環境為准了。


免責聲明!

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



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