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语句”内部的命令块,输出如下所示:
    《Bash else-If语句》

示例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 else-If语句》

通过输入不同的值来执行此示例,并检查结果。

        原文作者:Bash Shell教程
        原文地址: https://www.yiibai.com/bash/bash-else-if-statement.html
        本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
    点赞