Learn to Code via Tutorials on Repl.it!

← Back to all posts
Shell Scripting S10 : Control Statements-if,elif,else
sasivanga (14)

Session-10. Control Statements-if,elif,else

Control statements :
If statement
Case statement
While loop
For loop
Until loop
Break
Exit

If statements

simple if
If-ele
nested if
ladder if

If [ condition ]
Then
Action
fi

Case:

…..

Esca

x=10===> Assignment operator
X = 10 ===> before and after space ==comparison operator

#!/bin/bash
read -p "enter your name   : " name

if [  $name = "Shashi"  ] 
then
    echo "hello shahsi good morning"
fi
echo " how are you : $name "

Method 2:

If [ condition ];then
Action
fi

#!/bin/bash
read -p "enter your name   : " name

if [  $name = "Shashi"  ] ;then
    echo "hello shahsi good morning"
fi
echo " how are you : $name "

2)if-else

If [ condition ]
then
First action
else
Action 2
fi

3) Nested if

If [ condition1 ];then
First action
If[ condition2 ]; then
……..
If[ cond3 ]; then

------

else


fi

else

fi
fi

 Action 2

fi

4)ladder if:

If [ condition1 ]
then
First action
elif [ cond2 ]
then
Action 2
elif [ cond3 ]
then
Action 3
else
Default action
Fi

Greater number

#!/bin/bash
read -p "enter first number  : " a
read -p "enter 2nd number  : " b

if [  $a -gt $b ] ;then
    echo "Bigger number is $a"
else
    echo "Bigger number is $b"
fi



#!/bin/bash
read -p "enter first number  : " a
read -p "enter 2nd number  : " b
if [  $a -eq $b ] ;then
    echo "both numbers are equal"
elif [  $a -gt $b ] ;then
    echo "first number is  greater than second number"
else
    echo "second  number is  greater than first number"
Fi

#Find the greatest of three numbers 

#!/bin/bash
read -p "enter first number  : " a
read -p "enter 2nd number  : " b
read -p "enter 3rd number  : " c
if [  $a -gt $b  -a $a -gt $c] ;then
    echo "$a is the bigger name"
elif [  $b -gt $c ] ;then
    echo "$b   is  biggest"
else
    echo "$c is biggest"
fi


#Subject failed 

#!/bin/bash
read -p "enter first subject marks: " a
read -p "enter 2nd subject marks  : " b
read -p "enter 3rd subject marks  : " c
if [  $a -lt 35 ] ;then
    echo "1st subject failed"
elif [  $b -lt 35 ] ;then
    echo "2nd subject failed"
elif [  $c -lt 35 ] ;then
    echo "3rd subject failed"
else
    echo "Congrats you passed all  3subjects "
fi

Favorite brand and corresponding info :

Script +ve o r -ve number

#!/bin/bash

read -p "enter any interger number " n

if [ $n -lt 0 ] ; then

   echo "$n is negative number"

else

   echo "$n is postive number"

fi

Even number or not

#!/bin/bash
read -p "enter any interger number " n
if [ $[n%2] -eq 0 ] ; then
   echo "$n is even number"
else
   echo "$n is odd number"
fi