Unix-if-elif-statement

提供:Dev Guides
移動先:案内検索

Unix/Linux Shell-if …​ elif …​ fiステートメント

*if ... elif ... fi* ステートメントは、シェルが複数の条件から正しい決定を下せるようにする制御ステートメントの1レベルアドバンス形式です。

構文

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