天天看點

運維的shell小編(5) 第五章、Shell基本文法

Shell測試有test指令和[]方式,如果結果為0表示正确,否則錯誤。可以測試檔案狀态,數值比較,邏輯測試等。

測試檔案狀态:-f是否為檔案,-d是否為目錄,-l是否為連接配接檔案,-w是否具有寫的權限,-e是否存在。下面的test1不存在,2存在。

<a href="http://blog.51cto.com/attachment/201209/233738190.png" target="_blank"></a>

條件測試:格式[數值1  操作符  數值2]

常用操作符:-eq等于,-ne不等于,-gt大于,-lt小于,-le小于等于,-ge大于等于。記憶英語最好equal,greate,less。

注:[]左右必須留白格,

<a href="http://blog.51cto.com/attachment/201209/233807512.png" target="_blank"></a>

條件測試:

字元串比較格式:[字元串1  =或!=  字元串2]

邏輯測試:[表達式1] 操作符 [表達式2]

-a/&amp;&amp;表示邏輯與;-o/||表示邏輯或;!表示邏輯非

首先用if語句做判斷,判斷磁盤我們使用awk來進行過濾,我們這裡使用最基本的功能,如抓取第四行的第五個資料,然後取整比較,來判斷磁盤。

<a href="http://blog.51cto.com/attachment/201209/233830498.png" target="_blank"></a>

<a href="http://blog.51cto.com/attachment/201209/233843639.png" target="_blank"></a>

<a href="http://blog.51cto.com/attachment/201209/233906133.png" target="_blank"></a>

<a href="http://blog.51cto.com/attachment/201209/233915222.png" target="_blank"></a>

If的雙分支語句。我們可以使用判斷執行個體,如果3306端口打開則顯示打開資訊,否則重新開機mysql。

<a href="http://blog.51cto.com/attachment/201209/233929921.png" target="_blank"></a>

<a href="http://blog.51cto.com/attachment/201209/233953912.png" target="_blank"></a>

<a href="http://blog.51cto.com/attachment/201209/234005319.png" target="_blank"></a>

For語句,可以用來循環和取in裡的值

<a href="http://blog.51cto.com/attachment/201209/234017400.png" target="_blank"></a>

<a href="http://blog.51cto.com/attachment/201209/234034857.png" target="_blank"></a>

這裡介紹一下數學運算,可以用expr輸出結果,或執行$((運算))

<a href="http://blog.51cto.com/attachment/201209/234048441.png" target="_blank"></a>

While循環:包含如下兩種形式,形式1是先判斷後執行,例如批量加入客戶,然後再批量删除使用者。

<a href="http://blog.51cto.com/attachment/201209/234103181.png" target="_blank"></a>

<a href="http://blog.51cto.com/attachment/201209/234116545.png" target="_blank"></a>

<a href="http://blog.51cto.com/attachment/201209/234125234.png" target="_blank"></a>

Case多重分支語句:例如當執行./mydb.sh start時,啟動mysql;當執行./mydb.sh stop時,關閉mysql;如輸入其他資訊顯示幫助。*代表其它所有指令。

<a href="http://blog.51cto.com/attachment/201209/234137138.png" target="_blank"></a>

<a href="http://blog.51cto.com/attachment/201209/234147932.png" target="_blank"></a>

鍵盤輸入一個字元判斷是否為字母,數字或其它資訊。

<a href="http://blog.51cto.com/attachment/201209/234159230.png" target="_blank"></a>

Shift遷移語句:用于位置遷移将$1~$9一次左移。執行個體:将資料一次傳遞計算總和。./sum.sh 12 23 便可以得到結果。

<a href="http://blog.51cto.com/attachment/201209/234209773.png" target="_blank"></a>

Break和continue是使用者跳出循環。Break跳出循環體,continue跳出本次循環。

<a href="http://blog.51cto.com/attachment/201209/234222912.png" target="_blank"></a>

<a href="http://blog.51cto.com/attachment/201209/234233765.png" target="_blank"></a>

Shell函數是指需要經常調用的語句塊,即可成為函數。合理使用shell函數,可以明顯提高程式設計效率。

<a href="http://blog.51cto.com/attachment/201209/234250419.png" target="_blank"></a>

對于函數,指派要加載在函數裡面

<a href="http://blog.51cto.com/attachment/201209/234302489.png" target="_blank"></a>

本文轉自zsaisai 51CTO部落格,原文連結:http://blog.51cto.com/3402313/1009540