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
廣告