Unix / Linux Shell - L'instruction if ... elif ... fi

le if...elif...fi L'instruction est la forme avancée d'énoncé de contrôle à un niveau qui permet à Shell de prendre une décision correcte à partir de plusieurs conditions.

Syntaxe

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

Ce code est juste une série d' instructions if , où chaque if fait partie de la clause else de l'instruction précédente. Ici, les instructions sont exécutées sur la base de la condition vraie, si aucune condition n'est vraie, le bloc else est exécuté.

Exemple

#!/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

Lors de l'exécution, vous recevrez le résultat suivant -

a is less than b
unix-decision-making.htm