添加環境變量:https://www.cnblogs.com/lovychen/p/5583703.html
一、環境變量介紹:
在Linux系統中,環境變量按照其作用范圍不同大致可以分為系統級環境變量和用戶級環境變量。
- 系統級環境變量:每一個登錄到系統的用戶都能夠讀取到系統級的環境變量;
- 用戶級環境變量:每一個登錄到系統的用戶只能夠讀取屬於自己的用戶級的環境變量;
自然而然地,環境變量的配置文件也相應的被分成了系統級和用戶級兩種。
二、系統級:
1、/etc/profile
在系統啟動后第一個用戶登錄時運行,並從/etc/profile.d目錄的配置文件中搜集shell的設置,使用該文件配置的環境變量將應用於登錄到系統的每一個用戶。
提示:在Linux系統中,使用以下命令可以使配置文件立刻生效。
source /etc/profile echo $PATH
2、/etc/bashrc(Ubuntu和Debian中是/etc/bash.bashrc)
在 bash shell 打開時運行,修改該文件配置的環境變量將會影響所有用戶使用的bash shell。
注意:這里的bash shell有不同的類別,不同的類別所使用的環境變量配置文件也有所不同。
一般情況下,非登錄shell不會執行任何profile文件,非交互shell模式不會執行任何bashrc文件。
3、/etc/environment
在系統啟動時運行,用於配置與系統運行相關但與用戶無關的環境變量,修改該文件配置的環境變量將影響全局。
三、用戶級:
1、~/.profile(推薦首選)
~/.profile: executed by Bourne-compatible login shells.
當用戶登錄時執行,每個用戶都可以使用該文件來配置專屬於自己使用的shell信息。
2、~/.bashrc
~/.bashrc: executed by bash(1) for non-login shells.
當用戶登錄時以及每次打開新的shell時該文件都將被讀取,不推薦在這里配置用戶專用的環境變量,因為每開一個shell,該文件都會被讀取一次,效率肯定受影響。
生效用:source
bashrc和profile的差異
從上面的英文描述可以知道,bashrc和profile的差異在於:
注意:通常我們修改bashrc,有些linux的發行版本不一定有profile這個文件;
-
- 1. bashrc 是在系統啟動后就會自動運行。
- 2. profile 是在用戶登錄后才會運行。
- 3. 進行設置后,可運用source bashrc命令更新bashrc,也可運用source profile命令更新profile。
- 4. /etc/profile中設定的變量(全局)的可以作用於任何用戶,而~/.bashrc等中設定的變量(局部)只能繼承/etc/profile中的變量,他們是"父子"關系。
3、~/.bash_profile 或 ~./bash_login
~/.bash_profile or ~./bash_login - If one of these file exist, bash executes it rather then "~/.profile"
when it is started as a login shell. (Bash will prefer "~/.bash_profile" to "~/.bash_login").
However, these files won't influence a graphical session by default.
以上是ubuntu官網給出的關於~/.bash_profile 和 ~./bash_login 的說明,翻譯為中文:
~/.bash_profile 或 ~./bash_login -
如果有其中的一個文件存在的話, 當啟動的是一個登錄shell時,Bash 會執行該文件而不會執行~/.profile ;
如果兩個文件都存在的話,Bash 將會優先執行~/.bash_profile 而不是~/.bash_login ;
然而, 默認情況下,這些文件不會影響圖形會話。
4、~/.bash_logout
當每次退出系統(退出bash shell)時執行該文件。
注意:Linux系統使用 $VARIABLE_NAME 訪問環境變量,多個環境變量之間使用 “:”分隔,Windows系統使用 %VARIABLE_NAME% 訪問環境變量,多個環境變量之間使用 ; 分隔。
四、執行順序
一般情況下,Linux加載環境變量配置文件的執行順序為:
==> /etc/profile ==> ~/.bash_profile | ~/.bash_login | ~/.profile ==> ~/.bashrc ==> /etc/bashrc ==> ~/.bash_logout