在Linux的系統(tǒng)Shell腳本中使用if語句的方法

Bourne Shell 的 if 語句和大部分編程語言一樣 - 檢測條件是否真實,如果條件為真,shell 會執(zhí)行這個 if 語句指定的代碼塊,如果條件為假,shell 就會跳過 if 代碼塊,繼續(xù)執(zhí)行之后的代碼。
if 語句的語法:
then
command1
command2
……..
last_command
fi</p> <p>Example:</p> <p> #!/bin/bash
number=150
if [ $number -eq 150 ]
then
echo "Number is 150"
fi
if-else 語句:
除了標準的 if 語句之外,我們還可以加入 else 代碼塊來擴展 if 語句。這么做的主要目的是:如果 if 條件為真,執(zhí)行 if 語句里的代碼塊,如果 if 條件為假,執(zhí)行 else 語句里的代碼塊。
語法:
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
Example:
number=150
if [ $number -gt 250 ]
then
echo "Number is greater"
else
echo "Number is smaller"
fi
If..elif..else..fi 語句 (簡寫的 else if)
Bourne Shell 的 if 語句語法中,else 語句里的代碼塊會在 if 條件為假時執(zhí)行。我們還可以將 if 語句嵌套到一起,來實現(xiàn)多重條件的檢測。我們可以使用 elif 語句(else if 的縮寫)來構建多重條件的檢測。
語法 :
then
command1
command2
……..
last_command
elif [ 判斷條件2 ]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
Example :
number=150
if [ $number -gt 300 ]
then
echo "Number is greater"
elif [ $number -lt 300 ]
then
echo "Number is Smaller"
else
echo "Number is equal to actual value"
fi
多重 if 語句 :
If 和 else 語句可以在一個 bash 腳本里相互嵌套。關鍵詞 “fi” 表示里層 if 語句的結束,所有 if 語句必須使用 關鍵詞 “fi” 來結束。
基本 if 語句的嵌套語法:
then
command1
command2
……..
last_command
else
if [ 判斷條件2 ]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
fi
Example:
number=150
if [ $number -eq 150 ]
then
echo "Number is 150"
else
if [ $number -gt 150 ]
then
echo "Number is greater"
else
echo "'Number is smaller"
fi
fi
相關文章
- Shell不僅僅是一個命令,而且是其他命令的解釋器可以調試其他命令,從而完成編譯,下面為大家介紹下Linux系統(tǒng)中Shell命令應該怎么使用2015-05-28
Linux下如何實現(xiàn)shell多線程編程以提高應用程序的響應
Linux中多線程編程擁有提高應用程序的響應、使多cpu系統(tǒng)更加有效等優(yōu)點,下面為大家介紹有關shell多線程編程的例2014-12-10- 這篇文章主要介紹了Linux下查看使用的是哪種shell的方法匯總,本文總結了9種查看當前系統(tǒng)使用的是哪種shell的方法,需要的朋友可以參考下2014-11-17