Bash else-If語句


在本小節中,我們將了解如何在Bash指令碼中使用else-if(elif)語句來完成自動化任務。

Bash else-if語句用於多個條件。它是Bash if-else語句的補充。在Bash elif中,可以有多個elif塊,每個塊都有一個布林表示式。對於第一個if語句,如果條件為假,則檢查第二個if條件。

Bash Else If(elif)的語法

Bash shell指令碼中的else-if語句的語法是:

if [ condition ];  
then  
<commands>  
elif [ condition ];  
then  
<commands>  
else  
<commands>  
fi

if-else一樣,可以使用一組條件運算子連線的一個或多個條件。條件為真時執行命令集。如果沒有真實條件,則執行「 else語句」內的命令塊。

以下是一些演示else-if語句用法的範例:

範例1

下面的範例包含兩個不同的場景,第一個else-if語句的條件為true,在第二個else-if語句的條件為false

Bash指令碼檔案:elseif-demo1.sh

#!/bin/bash  

read -p "輸入數量:" num  

if [ $num -gt 100 ];  
then  
echo "可以打9折."  
elif [ $num -lt 100 ];  
then  
echo "可以打9.5折."  
else  
echo "幸運抽獎"  
echo "有資格免費獲得該物品"  
fi

執行上面範例程式碼。

  • 如果輸入110,則’if’的條件為true;如果輸入99,則’elif’的條件為true;如果輸入100,則沒有條件為真。在這種情況下,將執行「 else語句」內部的命令塊,輸出如下所示:

範例2

此範例演示了如何在Bash中的else-if語句中使用多個條件。使用bash邏輯運算子來加入多個條件。

Bash指令碼檔案:elseif-demo2.sh

#!/bin/bash  

read -p "Enter a number of quantity:" num  

if [ $num -gt 200 ];  
then  
echo "Eligible for 20% discount"  

elif [[ $num == 200 || $num == 100 ]];  
then  
echo "Lucky Draw Winner"  
echo "Eligible to get the item for free"  

elif [[ $num -gt 100 && $num -lt 200 ]];  
then  
echo "Eligible for 10% discount"  

elif [ $num -lt 100 ];  
then  
echo "No discount"  
fi

執行上面範例程式碼。如果輸入100,則輸出將如下所示:

通過輸入不同的值來執行此範例,並檢查結果。