歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> 在Linux的系統Shell腳本中使用if語句的方法

在Linux的系統Shell腳本中使用if語句的方法

日期:2017/3/1 17:42:06   编辑:SHELL編程

Bourne Shell 的 if 語句和大部分編程語言一樣 - 檢測條件是否真實,如果條件為真,shell 會執行這個 if 語句指定的代碼塊,如果條件為假,shell 就會跳過 if 代碼塊,繼續執行之後的代碼。
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 條件為真,執行 if 語句裡的代碼塊,如果 if 條件為假,執行 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 條件為假時執行。我們還可以將 if 語句嵌套到一起,來實現多重條件的檢測。我們可以使用 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

Copyright © Linux教程網 All Rights Reserved