ssh連接遠程主機執行腳本的環境變量問題

bash的四種模式

在man page的INVOCATION一節講述了bash的四種模式,bash會依據這四種模式而選擇加載不同的配置文件,而且加載的順序也有所不同。本文ssh問題的答案就存在於這幾種模式當中,所以在我們揭開謎底之前先來分析這些模式。

interactive + login shell

第一種模式是交互式的登陸shell,這裏面有兩個概念需要解釋:interactive和login:

login故名思義,即登陸,login shell是指用戶以非圖形化界面或者以ssh登陸到機器上時獲得的第一個shell,簡單些說就是需要輸入用戶名和密碼的shell。因此通常不管以何種方式登陸機器後用戶獲得的第一個shell就是login shell。

interactive意爲交互式,這也很好理解,interactive shell會有一個輸入提示符,並且它的標準輸入、輸出和錯誤輸出都會顯示在控制檯上。所以一般來說只要是需要用戶交互的,即一個命令一個命令的輸入的shell都是interactive shell。而如果無需用戶交互,它便是non-interactive shell。通常來說如bash script.sh此類執行腳本的命令就會啓動一個non-interactive shell,它不需要與用戶進行交互,執行完後它便會退出創建的shell。

那麼此模式最簡單的兩個例子爲:

  • 用戶直接登陸到機器獲得的第一個shell
  • 用戶使用ssh user@remote獲得的shell

加載配置文件

這種模式下,shell首先加載/etc/profile,然後再嘗試依次去加載下列三個配置文件之一,一旦找到其中一個便不再接着尋找

  • ~/.bash_profile
  • ~/.bash_login
  • ~/.profile

下面給出這個加載過程的僞代碼:

execute /etc/profile
IF ~/.bash_profile exists THEN
    execute ~/.bash_profile
ELSE
    IF ~/.bash_login exist THEN
        execute ~/.bash_login
    ELSE
        IF ~/.profile exist THEN
            execute ~/.profile
        END IF
    END IF
END IF

爲了驗證這個過程,我們來做一些測試。首先設計每個配置文件的內容如下:

user@remote > cat /etc/profile
echo @ /etc/profile
user@remote > cat ~/.bash_profile
echo @ ~/.bash_profile
user@remote > cat ~/.bash_login
echo @ ~/.bash_login
user@remote > cat ~/.profile
echo @ ~/.profile

然後打開一個login shell,注意,爲方便起見,這裏使用bash -l命令,它會打開一個login shell,在man bash中可以看到此參數的解釋:

-l Make bash act as if it had been invoked as a login shell

進入這個新的login shell,便會得到以下輸出:

@ /etc/profile
@ /home/user/.bash_profile

果然與文檔一致,bash首先會加載全局的配置文件/etc/profile,然後去查找~/.bash_profile,因爲其已經存在,所以剩下的兩個文件不再會被查找。

接下來移除~/.bash_profile,啓動login shell得到結果如下:

@ /etc/profile
@ /home/user/.bash_login

因爲沒有了~/.bash_profile的屏蔽,所以~/.bash_login被加載,但最後一個~/.profile仍被忽略。

再次移除~/.bash_login,啓動login shell的輸出結果爲:

@ /etc/profile
@ /home/user/.profile

~/.profile終於熬出頭,得見天日。通過以上三個實驗,配置文件的加載過程得到了驗證,除去/etc/profile首先被加載外,其餘三個文件的加載順序爲:~/.bash_profile~/.bash_login > ~/.profile,只要找到一個便終止查找。

前面說過,使用ssh也會得到一個login shell,所以如果在另外一臺機器上運行ssh user@remote時,也會得到上面一樣的結論。

配置文件的意義

那麼,爲什麼bash要弄得這麼複雜?每個配置文件存在的意義是什麼?

/etc/profile很好理解,它是一個全局的配置文件。後面三個位於用戶主目錄中的配置文件都針對用戶個人,也許你會問爲什麼要有這麼多,只用一個~/.profile不好麼?究竟每個文件有什麼意義呢?這是個好問題。

Cameron Newham和Bill Rosenblatt在他們的著作《Learning the bash Shell, 2nd Edition》的59頁解釋了原因:

bash allows two synonyms for .bash_profile: .bash_login, derived from the C shell’s file named .login, and .profile, derived from the Bourne shell and Korn shell files named .profile. Only one of these three is read when you log in. If .bash_profile doesn’t exist in your home directory, then bash will look for .bash_login. If that doesn’t exist it will look for .profile.

One advantage of bash’s ability to look for either synonym is that you can retain your .profile if you have been using the Bourne shell. If you need to add bash-specific commands, you can put them in .bash_profile followed by the command source .profile. When you log in, all the bash-specific commands will be executed and bash will source .profile, executing the remaining commands. If you decide to switch to using the Bourne shell you don’t have to modify your existing files. A similar approach was intended for .bash_login and the C shell .login, but due to differences in the basic syntax of the shells, this is not a good idea.

原來一切都是爲了兼容,這麼設計是爲了更好的應付在不同shell之間切換的場景。因爲bash完全兼容Bourne shell,所以.bash_profile.profile可以很好的處理bash和Bourne shell之間的切換。但是由於C shell和bash之間的基本語法存在着差異,作者認爲引入.bash_login並不是個好主意。所以由此我們可以得出這樣的最佳實踐:

  • 應該儘量杜絕使用.bash_login,如果已經創建,那麼需要創建.bash_profile來屏蔽它被調用
  • .bash_profile適合放置bash的專屬命令,可以在其最後讀取.profile,如此一來,便可以很好的在Bourne shell和bash之間切換了

non-interactive + login shell

第二種模式的shell爲non-interactive login shell,即非交互式的登陸shell,這種是不太常見的情況。一種創建此shell的方法爲:bash -l script.sh,前面提到過-l參數是將shell作爲一個login shell啓動,而執行腳本又使它爲non-interactive shell。

對於這種類型的shell,配置文件的加載與第一種完全一樣,在此不再贅述。

interactive + non-login shell

第三種模式爲交互式的非登陸shell,這種模式最常見的情況爲在一個已有shell中運行bash,此時會打開一個交互式的shell,而因爲不再需要登陸,因此不是login shell。

加載配置文件

對於此種情況,啓動shell時會去查找並加載/etc/bash.bashrc~/.bashrc文件。

爲了進行驗證,與第一種模式一樣,設計各配置文件內容如下:

user@remote > cat /etc/bash.bashrc
echo @ /etc/bash.bashrc
user@remote > cat ~/.bashrc
echo @ ~/.bashrc

然後我們啓動一個交互式的非登陸shell,直接運行bash即可,可以得到以下結果:

@ /etc/bash.bashrc
@ /home/user/.bashrc

由此非常容易的驗證了結論。

bashrc VS profile

從剛引入的兩個配置文件的存放路徑可以很容易的判斷,第一個文件是全局性的,第二個文件屬於當前用戶。在前面的模式當中,已經出現了幾種配置文件,多數是以profile命名的,那麼爲什麼這裏又增加兩個文件呢?這樣不會增加複雜度麼?我們來看看此處的文件和前面模式中的文件的區別。

首先看第一種模式中的profile類型文件,它是某個用戶唯一的用來設置全局環境變量的地方, 因爲用戶可以有多個shell比如bash, sh, zsh等, 但像環境變量這種其實只需要在統一的一個地方初始化就可以, 而這個地方就是profile,所以啓動一個login shell會加載此文件,後面由此shell中啓動的新shell進程如bash,sh,zsh等都可以由login shell中繼承環境變量等配置。

接下來看bashrc,其後綴rc的意思爲Run Commands,由名字可以推斷出,此處存放bash需要運行的命令,但注意,這些命令一般只用於交互式的shell,通常在這裏會設置交互所需要的所有信息,比如bash的補全、alias、顏色、提示符等等。

所以可以看出,引入多種配置文件完全是爲了更好的管理配置,每個文件各司其職,只做好自己的事情。

non-interactive + non-login shell

最後一種模式爲非交互非登陸的shell,創建這種shell典型有兩種方式:

  • bash script.sh
  • ssh user@remote command

這兩種都是創建一個shell,執行完腳本之後便退出,不再需要與用戶交互。

加載配置文件

對於這種模式而言,它會去尋找環境變量BASH_ENV,將變量的值作爲文件名進行查找,如果找到便加載它。

同樣,我們對其進行驗證。首先,測試該環境變量未定義時配置文件的加載情況,這裏需要一個測試腳本:

user@remote > cat ~/script.sh
echo Hello World

然後運行bash script.sh,將得到以下結果:

Hello World

從輸出結果可以得知,這個新啓動的bash進程並沒有加載前面提到的任何配置文件。接下來設置環境變量BASH_ENV

user@remote > export BASH_ENV=~/.bashrc

再次執行bash script.sh,結果爲:

@ /home/user/.bashrc
Hello World

果然,~/.bashrc被加載,而它是由環境變量BASH_ENV設定的。

更爲直觀的示圖

至此,四種模式下配置文件如何加載已經講完,因爲涉及的配置文件有些多,我們再以兩個圖來更爲直觀的進行描述:

第一張圖來自這篇文章,bash的每種模式會讀取其所在列的內容,首先執行A,然後是B,C。而B1,B2和B3表示只會執行第一個存在的文件:

+----------------+--------+-----------+---------------+
|                | login  |interactive|non-interactive|
|                |        |non-login  |non-login      |
+----------------+--------+-----------+---------------+
|/etc/profile    |   A    |           |               |
+----------------+--------+-----------+---------------+
|/etc/bash.bashrc|        |    A      |               |
+----------------+--------+-----------+---------------+
|~/.bashrc       |        |    B      |               |
+----------------+--------+-----------+---------------+
|~/.bash_profile |   B1   |           |               |
+----------------+--------+-----------+---------------+
|~/.bash_login   |   B2   |           |               |
+----------------+--------+-----------+---------------+
|~/.profile      |   B3   |           |               |
+----------------+--------+-----------+---------------+
|BASH_ENV        |        |           |       A       |
+----------------+--------+-----------+---------------+

上圖只給出了三種模式,原因是第一種login實際上已經包含了兩種,因爲這兩種模式下對配置文件的加載是一致的。

另外一篇文章給出了一個更直觀的圖:

Bash加載文件順序

上圖的情況稍稍複雜一些,因爲它使用了幾個關於配置文件的參數:--login--rcfile--noprofile--norc,這些參數的引入會使配置文件的加載稍稍發生改變,不過總體來說,不影響我們前面的討論,相信這張圖不會給你帶來更多的疑惑。

典型模式總結

爲了更好的理清這幾種模式,下面我們對一些典型的啓動方式各屬於什麼模式進行一個總結:

  • 登陸機器後的第一個shell:login + interactive
  • 新啓動一個shell進程,如運行bash:non-login + interactive
  • 執行腳本,如bash script.sh:non-login + non-interactive
  • 運行頭部有如#!/usr/bin/env bash的可執行文件,如./executable:non-login + non-interactive
  • 通過ssh登陸到遠程主機:login + interactive
  • 遠程執行腳本,如ssh user@remote script.sh:non-login + non-interactive
  • 遠程執行腳本,同時請求控制檯,如ssh user@remote -t 'echo $PWD':non-login + interactive
  • 在圖形化界面中打開terminal:
  • Linux上: non-login + interactive
  • Mac OS X上: login + interactive

相信你在理解了login和interactive的含義之後,應該會很容易對上面的啓動方式進行歸類。

再次嘗試

在介紹完bash的這些模式之後,我們再回頭來看文章開頭的問題。ssh user@remote ~/myscript.sh屬於哪一種模式?相信此時你可以非常輕鬆的回答出來:non-login + non-interactive。對於這種模式,bash會選擇加載$BASH_ENV的值所對應的文件,所以爲了讓它加載/etc/profile,可以設定:

user@remote > export BASH_ENV=/etc/profile

然後執行上面的命令,但是很遺憾,發現錯誤依舊存在。這是怎麼回事?彆着急,這並不是我們前面的介紹出錯了。仔細查看之後才發現腳本myscript.sh的第一行爲#!/usr/bin/env sh,注意看,它和前面提到的#!/usr/bin/env bash不一樣,可能就是這裏出了問題。我們先嚐試把它改成#!/usr/bin/env bash,再次執行,錯誤果然消失了,這與我們前面的分析結果一致。

第一行的這個語句有什麼用?設置成sh和bash有什麼區別?帶着這些疑問,再來查看man bash

If the program is a file beginning with #!, the remainder of the first line specifies an interpreter for the program.

它表示這個文件的解釋器,即用什麼程序來打開此文件,就好比Windows上雙擊一個文件時會以什麼程序打開一樣。因爲這裏不是bash,而是sh,那麼我們前面討論的都不復有效了,真糟糕。我們來看看這個sh的路徑:

user@remote > ll `which sh`
lrwxrwxrwx 1 root root 9 Apr 25  2014 /usr/bin/sh -> /bin/bash

原來sh只是bash的一個軟鏈接,既然如此,BASH_ENV應該是有效的啊,爲何此處無效?還是回到man bash,同樣在INVOCATION一節的下部看到了這樣的說明:

If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well. When invoked as an interactive login shell, or a non-interactive shell with the –login option, it first attempts to read and execute commands from /etc/profile and ~/.profile, in that order. The –noprofile option may be used to inhibit this behavior. When invoked as an interactive shell with the name sh, bash looks for the variable ENV, expands its value if it is defined, and uses the expanded value as the name of a file to read and execute. Since a shell invoked as sh does not attempt to read and execute commands from any other startup files, the –rcfile option has no effect. A non-interactive shell invoked with the name sh does not attempt to read any other startup files. When invoked as sh, bash enters posix mode after the startup files are read.

簡而言之,當bash以是sh命啓動時,即我們此處的情況,bash會儘可能的模仿sh,所以配置文件的加載變成了下面這樣:

  • interactive + login: 讀取/etc/profile~/.profile
  • non-interactive + login: 同上
  • interactive + non-login: 讀取ENV環境變量對應的文件
  • non-interactive + non-login: 不讀取任何文件

這樣便可以解釋爲什麼出錯了,因爲這裏屬於non-interactive + non-login,所以bash不會讀取任何文件,故而即使設置了BASH_ENV也不會起作用。所以爲了解決問題,只需要把sh換成bash,再設置環境變量BASH_ENV即可。

另外,其實我們還可以設置參數到第一行的解釋器中,如#!/bin/bash --login,如此一來,bash便會強制爲login shell,所以/etc/profile也會被加載。相比上面那種方法,這種更爲簡單。

配置文件建議

回顧一下前面提到的所有配置文件,總共有以下幾種:

  • /etc/profile
  • ~/.bash_profile
  • ~/.bash_login
  • ~/.profile
  • /etc/bash.bashrc
  • ~/.bashrc
  • $BASH_ENV
  • $ENV

不知你是否會有疑問,這麼多的配置文件,究竟每個文件裏面應該包含哪些配置,比如PATH應該在哪?提示符應該在哪配置?啓動的程序應該在哪?等等。所以在文章的最後,我搜羅了一些最佳實踐供各位參考。(這裏只討論屬於用戶個人的配置文件)

  • ~/.bash_profile:應該儘可能的簡單,通常會在最後加載.profile.bashrc(注意順序)
  • ~/.bash_login:在前面討論過,別用它
  • ~/.profile:此文件用於login shell,所有你想在整個用戶會話期間都有效的內容都應該放置於此,比如啓動進程,環境變量等
  • ~/.bashrc:只放置與bash有關的命令,所有與交互有關的命令都應該出現在此,比如bash的補全、alias、顏色、提示符等等。特別注意:別在這裏輸出任何內容(我們前面只是爲了演示,別學我哈)

寫在結尾

至此,我們詳細的討論完了bash的幾種工作模式,並且給出了配置文件內容的建議。通過這些模式的介紹,本文開始遇到的問題也很容易的得到了解決。以前雖然一直使用bash,但真的不清楚裏面包含了如此多的內容。同時感受到Linux的文檔的確做得非常細緻,在完全不需要其它安裝包的情況下,你就可以得到一個非常完善的開發環境,這也曾是Eric S. Raymond在其著作《UNIX編程藝術》中提到的:UNIX天生是一個非常完善的開發機器。本文幾乎所有的內容你都可以通過閱讀man page得到。最後,希望在這樣一個被妖魔化的特殊日子裏,這篇文章能夠爲你帶去一絲幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章