前言
這里討論的shell都是bash shell 使用哪種shell形式可以通過修改/etc/passwd 文件配置(bash sh csh)
討論的配置文件包括 :
/etc/profile
/etc/bashrc
~/.bash_login
~/.bash_profile
~/.profile
~/.bashrc
在shell以不同的形式打開時,加載以上不同配置文件
shell的幾種形式
登陸的維度劃分:login shell , non-login shell
交互的維度劃分:interactive shell , non-interactive shell
login shell 和 non-login shell
login shell
需要用戶名、密碼登錄后才能進(jìn)入的shell。在大多數(shù)情況下 ,遠(yuǎn)程終端工具(secureCRT xshell putty)通過ssh連接都是login shell
non-login shell
一般是在圖形界面中啟動一個終端shell
或者在login shell終端輸入bash 會打開一個新的shell,這個shell也是non-login的 或者通過su username 切換到新用戶得到一個non-login shell
切換
- 在login模式下 通過輸入"bash"即可打開一個non-login shell 如果是"bash --login" 則打開一個login shell
- 通過su - username 模式切換可以獲得一個login shell 如果不加"-" 如:su username 則獲得一個non-login shell
interactive shell 和 non-interactive shell
interactive shell
在大多數(shù)遠(yuǎn)程工具連接服務(wù)器后打開的都是interactive shell( 交互式shell ) 改模式下,shell等待你輸入命令并解釋和執(zhí)行這些命令,然后繼續(xù)等待下一個命令。
non-interactive shell
一般是指執(zhí)行shell腳本時的模式,通過"bash test.sh"這種形式執(zhí)行腳本文件,它并不與用戶交互 而是一次性執(zhí)行腳本 當(dāng)腳本執(zhí)行完畢 shell即終止。
通過"echo $-"可以查看當(dāng)前是否為交互式shell。 輸出為"himBH" 標(biāo)識interactive shell 。如果為 "hB" 表示non-interactive shell
一般以"#!/bin/bash" 開頭的shell腳本是non-login non-interactive shell
如果以"#!/bin/bash --login"開頭的shell腳本時login non-interactive shell
不同登錄模式所讀取的配置文件不同
一、login shell (包括interactive shell或者non-interactive shell)讀取:
- /etc/profile
這是全局的配置,不管哪個用戶登錄,都會讀取
- ~/.bash_profile 或~/.bash_login 或~/.profile
按照順序 找到其中任意一個即執(zhí)行讀取,不會再找下一個了。
查看這三個文件的內(nèi)容可以發(fā)現(xiàn)基本上都是去讀取~/.bashrc這個文件
# .bash_profile
2
3 # Get the aliases and functions
4 if [ -f ~/.bashrc ]; then
5 . ~/.bashrc
6 fi
7
8 # User specific environment and startup programs
查看~/.bashrc文件可以發(fā)現(xiàn)它是去加載/etc/bashrc
# .bashrc
2
3 # User specific aliases and functions
4
5 alias rm='rm -i'
6 alias cp='cp -i'
7 alias mv='mv -i'
8
9 # Source global definitions
10 if [ -f /etc/bashrc ]; then
11 . /etc/bashrc
12 fi
二、non-login shell
- ~/.bashrc
non-login shell只會讀取該配置
三、non-interactive non-login shell
這種模式下(執(zhí)行最普通的shell腳本 bash test.sh 即時該模式) 不讀取任何配置文件,而是會讀取環(huán)境變量 BASH_ENV所指向的腳本文件。通過以下腳本驗(yàn)證
//創(chuàng)建臨時環(huán)境變量BASH_ENV
[root@xxx~]# export BASH_ENV='~/hello.sh'
//編寫腳本hello.sh 內(nèi)容如下
1 #!/bin/bash
2 echo "this is hello.sh"
//編寫腳本test.sh 內(nèi)容如下
1 #!/bin/bash
2 echo "this is test.sh"
[root@xxx ~]# bash test.sh
this is hello.sh
this is test.sh
環(huán)境變量修改示例
通過對上面幾個概念的理解,在配置環(huán)境變量的時候,我們應(yīng)該盡量不去修改/etc/profile文件,因?yàn)檫@是對全部登錄用戶都有效的。對于~/.bash_profile , ~/.bash_login , ~/.profile 通過將他們都指向~/.bashrc 再通過修改用戶目錄下的~/.bashrc來新增或者修改環(huán)境變量
[@xxx xxx]#vim ~/.bashrc
//在打開的.bashrc文件中增加一個邊境變量入 /home/java/jdk-8/bin
export JDK_ROOT=/home/java/jdk-8/bin
//最后一句 將上面定義的JDK_ROOT通過:拼接到$PATH之后即可,添加多個環(huán)境變量的時候 每個都用:拼接即可
export PATH=$PATH:$JDK_ROOT
//讓修改的環(huán)境變量立即生效
[@xxx xxx]#source ~/.bashrc