📜  Bash 脚本 – Else If 语句

📅  最后修改于: 2022-05-13 01:57:34.329000             🧑  作者: Mango

Bash 脚本 – Else If 语句

在本文中,我们将讨论如何为 Else If 语句编写 bash 脚本。

条件语句:根据特定条件执行特定功能的语句称为条件语句。在 bash 脚本中,我们有几个条件语句,如 IF、IF-ELSE、IF-ELSE-IF 等。每个语句都有其工作方式,我们根据需要使用它们。

IF 声明

当需要仅检查条件时使用此语句。如果条件成立,则写入 if 块中的语句将被执行。

句法:

if (condition)
then
 statement
fi

代码:

if [ 15 -gt 10 ]
then  
# If variable less than 10  
   echo "a is greater than 10"

fi 

该程序将检查条件,15 是否大于 10。如果 15 大于 10,则在 IF 块中写入的语句将打印在屏幕上。

输出:

a is greater than 10

IF-ELSE 语句

如在 If 语句中所见,如果条件为真,则执行 IF 语句块,但如果条件为假,则不返回或执行任何内容。如果我们希望程序在 IF 语句条件为假之后执行某些操作,我们在 If 语句之后使用 ELSE 语句。

句法:

if [condition ]
then  
    If statement
else
    ELSE statement
fi 
  • 如果条件为真:将执行 IF 语句。
  • 如果条件为假:ELSE 语句将被执行。

代码:

if [ 5 -gt 10 ]
then  
# If variable less than 10  
   echo "number is greater than 10"
else
   echo "number is less than 10"
fi 

输出:

number is less than 10

ELIF (ELSE IF) 语句

ELIF 是 bash 脚本中用于 ELSE IF 语句的关键字。如果在一个循环中,如果存在两个以上的条件且仅通过使用 IF-ELSE 语句无法解决,则使用 ELIF。可以在一个 if-else 循环中定义多个 ELIF 条件。

ELIF 语法:

if [ condition1 ]
then
       statement1
 elif [ condition2 ]
then
       statement2
 elif [condition3 ]
then
       statement3
else
      statement_n
fi

代码:

#!/bin/bash
 # Initializing the variable
 a=20
 if [ $a < 10 ] 
then  
      # If variable less than 10    
      echo "a is less than 10" 
elif [ $a < 25 ] 
then  
      # If variable less than 25  
      echo "a is less than 25" 
else   
     # If variable is greater than 25   
     echo "a is greater than 25"  
fi 

输出:

a is greater than 25

嵌套语句

如果一个或多个条件语句写在另一个语句中,这称为嵌套语句,就像另一个 IF 语句中的 IF 语句一样。

语法(嵌套 IF):

If [condition]
then 
      if [condition_2]
      then 
            statement_1
      
      fi
fi

例子:

#!/bin/bash
#Initializing the variable

if [ 12 -gt 10 ]
then
   if [ 12 -gt 15]
   then
       echo "number is greater than 15"

   else
       echo "number is less than 15"
   fi
fi 

输出:

number is less than 15