位置:首頁 > 其他技術 > Shell > Shell if...elif...fi 語句

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