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 語句每一個語句else子句的一部分。下面語句是執行的基礎上的真實情況,如果條件不為 ture,則執行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