欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

開源中文社區(qū)   發(fā)布時間:2015-06-15 16:58:13   作者:Pradeep Kumar   我要評論
這篇文章主要介紹了在Linux的系統(tǒng)Shell腳本中使用if語句的方法,Bourne Shell是Unix上采用的腳本,也是Debian系的Linux系統(tǒng)bash shell的基礎,需要的朋友可以參考下

Bourne Shell 的 if 語句和大部分編程語言一樣 - 檢測條件是否真實,如果條件為真,shell 會執(zhí)行這個 if 語句指定的代碼塊,如果條件為假,shell 就會跳過 if 代碼塊,繼續(xù)執(zhí)行之后的代碼。
2015615170540856.png (300×358)

if 語句的語法:

   

復制代碼
代碼如下:
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 語句里的代碼塊。
語法:

   

復制代碼
代碼如下:
if [ 判斷條件 ]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi

Example:

   

復制代碼
代碼如下:
#!/bin/bash
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 的縮寫)來構建多重條件的檢測。
語法 :

   

復制代碼
代碼如下:
if [ 判斷條件1 ]
then
command1
command2
……..
last_command
elif [ 判斷條件2 ]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi

Example :

   

復制代碼
代碼如下:
#!/bin/bash
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 語句的嵌套語法:

   

復制代碼
代碼如下:
if [ 判斷條件1 ]
then
command1
command2
……..
last_command
else
if [ 判斷條件2 ]
then
command1
command2
……..
last_command
else
command1
command2
……..
last_command
fi
fi

Example:

   

復制代碼
代碼如下:
#!/bin/bash
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

相關文章

最新評論