天天看點

bash與source等特點和差別

如圖大家可以看到用./方式執行完腳本後,腳本内的所有環境變量均不影響當時的SHELL環境變量,而使用source則完全相反的效果。這樣簡單的測試相信大家對source和.的差別應該清晰明了了吧。其實,Linux下執行腳本的方式還有bash + filename的方式,那麼三者究竟有什麼差別呢?

1、source指令用法:

source FileName

作用:

在目前bash環境下讀取并執行FileName中的指令。該filename檔案可以<code>無</code>執行權限”

注:該指令通常用指令“.”來替代。

如:source .bash_profile    . .bash_profile兩者等效。 source(或點)指令通常用于重新執行剛修改的初始化文檔。 source指令(從 C Shell 而來)是bash shell的内置指令。 點指令,就是個點符号,(從Bourne Shell而來)。

2、sh和bash指令用法:

sh FileName   bash FileName

打開新的子shell,讀取并執行FileName中的指令。該filename檔案可以<code>無</code>“執行權限”  注:兩者在執行檔案時的不同,是分别用自己的shell來跑檔案。

sh使用“-n”選項進行shell腳本的文法檢查,使用“-x”選項實作shell腳本逐條語句的跟蹤,

可以巧妙地利用shell的内置變量增強“-x”選項的輸出資訊等。

3、./的指令用法:

./FileName

打開一個子shell來讀取并執行FileName中指令。

注:運作一個shell腳本時會啟動另一個指令解釋器.

每個shell腳本有效地運作在父shell(parent shell)的一個子程序裡. 這個父shell是指在一個控制終端或在一個xterm視窗中給你指令訓示符的程序.shell腳本也可以啟動他自已的子程序. 這些子shell(即子程序)使腳本并行地,有效率地地同時運作腳本内的多個子任務.

常用的shell的嵌入指令(内部指令)有如下這些,

<code>: 空,永遠傳回為</code><code>true</code> <code>.   從目前shell中執行操作</code> <code>break</code> <code>退出</code><code>for</code><code>、</code><code>while</code><code>、</code><code>until</code><code>或</code><code>case</code><code>語句</code> <code>cd</code> <code>改變到目前目錄</code> <code>continue</code> <code>執行循環的下一步</code> <code>echo</code> <code>回報資訊到标準輸出</code> <code>eval</code> <code>讀取參數,執行結果指令</code> <code>exec</code> <code>執行指令,但不在目前shell</code> <code>exit</code> <code>退出目前shell</code> <code>export</code> <code>導出變量,使目前shell可利用它</code> <code>pwd</code> <code>顯示目前目錄</code> <code>read</code> <code>從标準輸入讀取一行文本</code> <code>readonly</code> <code>使變量隻讀</code> <code>return</code> <code>退出函數并帶有傳回值</code> <code>set</code> <code>控制各種參數到标準輸出的顯示</code> <code>shift</code> <code>指令行參數向左偏移一個</code> <code>test</code> <code>評估條件表達式</code> <code>times</code> <code>顯示shell運作過程的使用者和系統時間</code> <code>trap</code> <code>當捕獲信号時運作指定指令</code> <code>ulimit</code> <code>顯示或設定shell資源</code> <code>umask</code> <code>顯示或設定預設檔案建立模式</code> <code>unset</code> <code>從shell記憶體中删除變量或函數</code> <code>wait 等待直到子程序運作完畢</code>

直接執行enable指令也可以得到所有的内部指令清單。

本文轉自 tianya1993 51CTO部落格,原文連結:http://blog.51cto.com/dreamlinux/1837083,如需轉載請自行聯系原作者

繼續閱讀