If…elif…else Statement in Shell Script

 If…elif…else Statement

  • This is one of the type of selection statement. 

Note

  • It is an important to note that, the simple if, if else and if-elif-else statements should be closed by fi keyword.

Syntax

if [ condition ]

then

     true statement

elif [ condition ]

then

     true statement

else

     false statement

fi


Example 1 - Shell Style Code
Biggest of Three Numbers

Source Code

echo "Enter the inputs: "

read a b c

if [ $a -gt $b -a $a -gt $c ]        # -a indicates logical AND
then
    echo "$a is big"
elif [ $b -gt $c ]
then
    echo "$b is big"
else
    echo "$c is big"
fi

Output

NOTE

  • It is not possible to directly use logical operator symbols in shell script.
  • The statement below the shows the example

Logical Operators

    Operator                         Operators in Shell   

    Logical AND                    &&                 -a

    Logical OR                       ||                    -o

  • You can use either && or option -a for logical AND operation in shell script.

using -a

  • Here, all the conditions should be placed in single [ ] operator

using &&

  • Here, each the condition should be placed in separate [ ] operator.


Example 2 - C Style Code in Shell Script
Biggest of Three Numbers

Source Code

echo "---------------------------"

echo -e "\t C Style in Shell"

echo "---------------------------"

echo "Enter the inputs: "

read a b c

if ((a>b))&&((a>c))

then

    echo "$a is bigger"

elif ((b>c))

then

    echo "$b is bigger"

else

    echo "$c is bigger"

fi


Output



























Video Example


Comments

Popular posts from this blog

Vivo V30 Pro 5G

Motorola G14 4G Review - Best Budget Smartphone

Xiaomi 14 - Features, Price