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,則輸出將如下所示:

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


上一篇: Bash if-else語句 下一篇: Bash case語句