歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> linux下設定環境變量的方法介紹

linux下設定環境變量的方法介紹

日期:2017/3/1 18:05:50   编辑:Linux技術
那麼需要將export命令寫入某個系統文件中,擁有這種功能的文件常見的有如下幾個:
/etc/environment 或 /etc/profile 或 ~/.profile 或 /etc/bash.bashrc 或 ~/.bashrc等。
有這麼多可以用,到底它們有什麼區別,誰先誰後呢?
首先,來看看這幾個文件都是干什麼的:
1./etc/environment–>是系統在登錄時讀取的第一個文件,用於為所有進程設置環境變量。系統使用此文件時並不是執行此文件中的命 令,而是根據KEY=VALUE模式的代碼,對KEY賦值以VALUE,因此文件中如果要定義PATH環境變量,只需加入一行形如 PATH=$PATH:/xxx/bin的代碼即可。
2./etc/profile–>是系統登錄時執行的第二個文件,可以用於設定針對全系統所有用戶的環境變量。
3.~/.profile–>是對應當前登錄用戶的profile文件,用於定制當前用戶的個人工作環境。
4./etc/bash.bashrc–>是針對所有用戶的bash初始化文件,在此中設定的環境變量將應用於所有用戶的shell中,此文件會在用戶每次打開shell時執行一次。
5.~/.bashrc–>是對應當前登錄用戶的bash初始化文件,當用戶每次打開shell時,系統都會執行此文件一次。
那麼根據以上描述,這幾個文件的執行先後順序應當是:
/etc/enviroment –>/etc/profile –>~/.profile –>/etc/bash.bashrc–> ~/.bashrc
為了驗證此順序是否正確,這裡可以做一個小試驗,假定我們登錄的用戶名為xyz。在/etc/environment中加入一行:
ENV_MSG=”this is /etc/environment”
這樣也就是添加了一個環境變量ENV_MSG,然後在/etc/profile中加入兩行代碼:
echo $ENV_MSG >> /home/xyz/log.txt
echo “this is /etc/profile” >> /home/xyz/log.txt
這樣,如果/etc/environment在profile之前被系統讀取,則在/home/xyz/log.txt 中會先後打印出EVN_MSG的值和 this is /etc/profile這兩條消息。
在/home/xyz/.profile中加入一行代碼:
echo “this is .profile” >> /home/xyz/log.txt
在/etc/bash.bashrc中加入一行代碼:
echo “this is /etc/bash.bashrc” >> /home/xyz/log.txt
在/home/xyz/.bashrc中加入一行代碼:
echo “this is .bashrc” >> /home/xyz/log.txt
然後,重啟計算機,看看log.txt文件中會是什麼樣子。
啟動計算機後以xyz用戶登錄並立即打開/home/xyz/log.txt,可以看到文件中有如下三行消息:
this is /etc/environment
this is /etc/profile
this is .profile
這說明系統在啟動登錄的過程中依次讀取執行了/etc/enviroment 、/etc/profile和~/.profile中的內容。
然後打開一個shell窗口,log文件中就會增加兩行消息:
this is /etc/bash.bashrc
this is .bashrc
這說明在打開shell過程中,系統又依次執行/etc/bash.bashrc和~/.bashrc。如果關閉shell窗口後再次打開一個新的 shell窗口,則log文件中會又增加兩行同樣的消息。由此可以獲知,每次打開一個新shell,系統都會重復執行這兩個文件,而不會再動那頭三個文件 的內容。
接下來我們再打開/etc/environment ,把剛才寫入的那行改成ENV_MSG=”this is not /etc/environment”,然後注銷,重新以xyz登錄,結果會發現log文件中會又多了三行:
this is not /etc/environment
this is /etc/profile
this is .profile
這也就看出來,注銷重登錄也會引發系統對這三個文件的讀取與執行。
不過,如果按下Ctrl+Alt+F1,然後登錄xyz,那麼log文件中會多出來如下幾行,這又是怎麼回事呢?
this is /etc/bash.bashrc
this is /etc/environment
this is /etc/profile
this is .bashrc
this is .profile
Copyright © Linux教程網 All Rights Reserved