Bash If、Elif 和 If Else 举例说明

Bash 脚本对于简化系统管理员、开发人员和 L​​inux 用户的生活至关重要。bash 脚本的一个组成部分是条件语句,即 if、else if 和 if else (elif) 语句。这些条件语句使 Linux 用户能够根据 bash 脚本内使用的不同条件做出决定,从而提供急需的灵活性和效率。也就是说,让我们通过示例来了解如何使用 If、Elif 和 If Else bash 语句。

如何在 Bash 脚本中使用 If 语句

在 bash 脚本中用于做出决定的最常见和基本的条件语句是“if”语句。这主要在需要检查某个条件是否满足时使用。在 bash 中使用 if 语句的语法是:

if [[ <condition> ]]
then
    <statement>
fi

在上面的语法中,只有满足<条件>时才会执行<语句>。例如,如果您需要在检查用户输入值是否小于 10 后在控制台上打印一条消息:

#!/bin/bash

echo -n "Enter a number: "
read num

if [[ $num -lt 20 ]]
then
  echo "The value is less than 20."
fi

执行上述脚本时,将检查用户输入的值是否小于 20。如果小于 20,则“该值小于 20”。被打印为输出。

在 Linux bash 脚本中使用 if 作为条件语句来检查 netered 数是否小于 20

如何在 Bash 脚本中使用 If Else 语句

所以利用if语句,只要满足某个条件就可以执行某种操作。但有时如果条件不满足,您可能需要执行某项操作。为此,您可以将“else”条件语句与 if 语句结合使用,为Linux 发行版的 bash 脚本添加更多灵活性。使用 else 语句的语法是:

if [[ <conditon> ]]
then
  <statement_to_execute_if_condition_is_true>
else
  <statement_to_execute_if_condition_is_false>
fi

例如,要检查用户是否有资格投票:

#!/bin/bash

echo "Please enter your age:"
read age

if [ "$age" -ge 18 ]; then
  echo "Congratulations! You are eligible to vote."
else
  echo "Sorry, you are not eligible to vote yet."
fi
使用 bash 脚本检查投票资格

如何在 Bash 脚本中使用 Else If (Elif)

虽然 if-else 条件构造非常适合检查一个条件并相应地执行任务,但如果您需要测试多个条件怎么办?对于这种情况,“else if”或“elif”语句就起作用了。使用 elif,您可以测试多个条件并相应地修改 bash 脚本。在 bash 中使用 elif 语句的语法是:

if [ condition_1 ]
then

    <statements_to_follow_if_condition_1_is_true>
elif [ condition_2 ]
then

    <statements_to_follow_if_condition_2_is_true>
else

    <statements_to_follow_if_all_conditions_are_false>
fi

例如:

#!/bin/bash


echo -n "Enter a fruit name: "
read fruit

if [ "$fruit" = "apple" ]
then
    echo "It's an apple."
elif [ "$fruit" = "banana" ]
then
    echo "It's a banana."
else
    echo "It's neither an apple nor a banana."
fi
在 Linux bash 脚本中使用 elif 作为条件语句

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注