Bash if-else语句

在本小节中,我们将了解如何在Bash脚本中使用if-else语句来完成自动化任务。

Bash if-else语句用于在语句的顺序执行流程中执行条件任务。有时,如果if条件为真,我们想处理一组特定的语句,但是如果if条件为假,则要处理另一组语句。要执行此类操作,可以应用if-else机制。们可以使用if语句应用条件。

if-else语法

Bash Shell脚本中if-else语句的语法定义如下:

if [ condition ];  
then  
   <if block commands>  
else  
  <else block commands>  
fi

以上语法有几个要点:

  • 可以使用一组使用条件运算符连接的一个或多个条件。
  • 其他块命令包括一组在条件为假时执行的动作。
  • 条件表达式后的分号(;)是必须的。

参考以下示例,演示如何在Bash脚本中使用if-else语句:

示例1
下面的示例包含两个不同的场景,在第一个if-else语句中条件为true,在第二个if-else语句中条件为false

脚本文件:ifelse-demo1.sh

#!/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语句》

在第一个if-else表达式中,条件(10 -gt 3)为true,因此执行if块中的语句。而在另一个if-else表达式中,条件(3 -gt 10)为false,因此执行else块中的语句。

示例2
在此示例中,演示如何在Bash中的if-else语句中使用多个条件。使用bash逻辑运算符来加入多个条件。
脚本文件:ifelse-demo2.sh

#!/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语句》

在一行if-else语句

可以在一行中编写完整的if-else语句以及命令。需要遵循以下一些规则才能在一行中使用if-else语句:

  • ifelse块的语句末尾使用分号(;)。
  • 使用空格作为分隔符来追加其他语句。

下面给出一个示例,演示如何在单行中使用if-else语句:

示例

脚本文件:ifelse-single-line.sh

#!/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

执行上面示例代码,得到以下结果:
《Bash if-else语句》

嵌套if-else语句

与嵌套的if语句一样,if-else语句也可以在另一个if-else语句中使用。在Bash脚本中将它称为嵌套if-else

下面是一个示例,演示如何在Bash中嵌套if-else语句。

脚本文件:ifelse-nested.sh

#!/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

执行上面示例代码,得到以下结果:
《Bash if-else语句》

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