Bash教程

Bash Else If

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 语句的条件为真,而第二个 else-if 语句的条件为假。
Bash 脚本
#!/bin/bash
read-p "Enter a number of quantity:" num
if [ $num-gt 100 ];
then
echo "Eligible for 10% discount"
elif [ $num-lt 100 ];
then
echo "Eligible for 5% discount"
else
echo "Lucky Draw Winner"
echo "Eligible to get the item for free"
fi
输出
如果我们输入数量为 110,则 'if statement' 的条件评估为真,输出如下所示: Bash Else If 如果我们输入数量为 90,则"elif 语句"的条件评估为真,输出如下所示: Bash Else If 如果我们输入数量为 100,则任何条件都不成立。在这种情况下,将执行"else 语句"中的命令块,输出如下所示: Bash Else If
这就是基本的 bash else-if 的工作原理。

示例 2

此示例演示如何在 Bash 中通过 else-if 语句使用多个条件。我们使用 bash 逻辑运算符来连接多个条件。
Bash 脚本
#!/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
注意: 需要注意的是else块是可选的。
输出
如果我们输入数量为100,则输出将如下所示:
Bash Else If
通过输入不同的值来试试这个例子并检查结果。

结论

在本主题中,我们通过示例了解了 Bash else-if 语句的语法和用法。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4