Unix/Linux Shell - if...elif...fi 语句



if...elif...fi 语句是控制语句的一种更高级的形式,它允许 Shell 在多种条件下做出正确的决策。

语法

if [ expression 1 ]
then
   Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
   Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
   Statement(s) to be executed if expression 3 is true
else
   Statement(s) to be executed if no expression is true
fi

这段代码只是一系列的 if 语句,其中每个 if 都是前一个语句的 else 子句的一部分。根据真值条件执行语句,如果所有条件都不成立,则执行 else 代码块。

示例

#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
   echo "a is equal to b"
elif [ $a -gt $b ]
then
   echo "a is greater than b"
elif [ $a -lt $b ]
then
   echo "a is less than b"
else
   echo "None of the condition met"
fi

执行后,您将收到以下结果:

a is less than b
unix-decision-making.htm
广告