Shell Script Conditional Statements (if-elif-else )

We use conditional statements to compare a value with other value(s) based on the condition to make decision.

Syntax for if else conditional statement:

 if [ condition ]; then
   command
 else
   command
 fi

If there are more than 2 conditions then we have to use elif:

 if [ condition ]; then
   command
 elif [ condtion ]; then
   command
 else
   command
 fi

Example of if else condition:

!/usr/bin/env bash
 FRUIT_NAME=Olive
 if [ "$FRUIT_NAME" = "Olive" ]; then
   echo "The fruit name is Olive"
 else
   echo "The fruit is not Olive"
 fi

 # Example with if elif else
 AGE=10
 if [ $AGE -lt 13 ]; then
   echo "You're a child"
 elif [ $AGE -ge 13 ] && [ $AGE -lt 19 ]; then
   echo "You're a teenager"
 else
   echo "You're a perfect fit!"
 fi

Save the code as if_elif_else.sh .

Run the if_elif_else.sh file like:

$ bash if_elif_else.sh

Output:

The fruit name is Olive
You're a child

Follow us on social media