Bash教程

Bash If Else

Bash If Else

在本主题中,我们将了解如何在 Bash 脚本中使用 if-else 语句来完成我们的自动化任务。
Bash if-else 语句用于在语句执行的顺序流中执行条件任务。有时,如果条件为真,我们希望处理一组特定的语句,如果条件为假,则处理另一组语句。要执行此类操作,我们可以应用 if-else 机制。我们可以用"if 语句"来应用条件。

Bash If Else 语法

Bash Shell 脚本中 if-else 语句的语法可以定义为下面:
if [ condition ];
then
   <if block commands>
else
  <else block commands>
fi

要记住的要点

我们可以使用一组使用条件运算符连接的一个或多个条件。 Else 块命令包括一组要在条件为假时执行的操作。 条件表达式后的分号(;) 是必须的。
查看以下示例,演示如何在 Bash 脚本中使用 if-else 语句:

示例 1

以下示例包括两种不同的情况,在第一个 if-else 语句中,条件为真,在第二个 if-else 语句中,条件为假。
#!/bin/bash
#when the condition is true
if [ 10-gt 3 ];
then
  echo "10 is greater than 3."
else
  echo "10 is not greater than 3."
fi
#when the condition is false
if [ 3-gt 10 ];
then
  echo "3 is greater than 10."
else
  echo "3 is not greater than 10."
fi
输出
Bash If Else Statement
在第一个 if-else 表达式中,条件( 10-gt 3 ) 为真,因此执行 if 块中的语句。而在另一个 if-else 表达式中,条件( 3-gt 10 ) 为假,因此执行 else 块中的语句。

示例 2

在这个例子中,我们解释了如何在 Bash 中的 if-else 语句中使用多个条件。我们使用 bash 逻辑运算符来连接多个条件。
#!/bin/bash
# When condition is true
# true && false || false || true
if [[ 10-gt 9 && 10 == 9 || 2-lt 1 || 25-gt 20 ]];
then
  echo "Given condition is true."
else
  echo "Given condition is false."
fi
# When condition is false
#TRUE && false || false || true
if [[ 10-gt 9 && 10 == 8 || 3-gt 4 || 8-gt 8 ]];
then
  echo "Given condition is true."
else
  echo "Given condition is not true."
fi
输出
Bash If Else Statement

Bash If Else 语句在一行中

我们可以在一行中编写完整的"if-else 语句"以及命令。您需要按照给定的规则在一行中使用 if-else 语句:
在 if 和 else 块中的语句末尾使用分号(;)。 使用空格作为分隔符来附加所有语句。
下面给出了一个示例,演示如何在一行中使用 if-else 语句:

示例

#!/bin/bash
read-p "Enter a value:" value
if [ $value-gt 9 ]; then echo "The value you typed is greater than 9."; else echo "The value you typed is not greater than 9."; fi
输出
当我们输入一个值为 25 时,输出将如下所示:
Bash If Else Statement

Bash Nested If Else

就像嵌套 if 语句一样,if-else语句也可以在另一个 if-else 语句中使用。在 Bash 脚本中,它被称为嵌套 if-else。
以下是解释如何在 Bash 中使用嵌套 if-else 语句的示例:

示例

#!/bin/bash
read-p "Enter a value:" value
if [ $value-gt 9 ];
then
  if [ $value-lt 11 ];
  then
     echo "$value>9, $value<11"
  else
    echo "The value you typed is greater than 9."
  fi
else echo "The value you typed is not greater than 9."
fi
输出
如果我们输入 10 作为值,那么输出将如下所示:
Bash If Else Statement

结论

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