无涯教程-Linux - If-elif 语句函数

81 阅读1分钟

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

If-elif - 语法

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子句的一部分。这里的语句是基于TRUE条件执行的,如果没有一个条件为TRUE,则执行else块。

If-elif - 示例

#!/bin/sh

a=10 b=20

if [ a</span><spanclass="pun">==</span><spanclass="pln">a </span><span class="pun">==</span><span class="pln"> b ] then echo "a is equal to b" elif [ a</span><spanclass="pun"></span><spanclass="pln">gta </span><span class="pun">-</span><span class="pln">gt b ] then echo "a is greater than b" elif [ a</span><spanclass="pun"></span><spanclass="pln">lta </span><span class="pun">-</span><span class="pln">lt b ] then echo "a is less than b" else echo "None of the condition met" fi

执行后,您将收到以下输出-

a is less than b

参考链接

www.learnfk.com/linux/linux…