Bash Shell Script – 2

Bash Shell Script - 2

Today we are going to see how to use if statement in bash shell scripting.

before going to work with if statement, we should know the options which will be used in if statement to compare conditions.

-gt :    greater than
-lt  :    less than
-eq :   equal too
-ge :   greater than or equal
-le  :   less than or equal

We are going to see a script with a simple if statement.

From the below script we are going to check given number is equal to 100 or not and using read command to get keyboard interaction while running the script.
It will read the number from our keyboard interaction and store it in a variable called number. Then will check for the condition, which we mentioned in if statement and display the string.

create a file called ifstat.sh using vi

#vi ifstat.sh

#!/bin/bash
echo “Enter a numeric value”
read number
if [ $number -eq 100 ]
then
echo “Numeric value is 100”
else
echo “Numeric values is not equal to 100”
fi

We can use elif, if we need to execute more than one statement for if condition.

For the same numeric value validation we are going to change use this elif  option.

#vi ifstat1.sh

#!/bin/bash
echo “Enter a numeric value”
read number
if [ $number -eq 100 ]
then
echo “Numeric value is 100”
elif [ $number -gt 100 ]
then
echo “Numeric values is greater then 100”
elif [ $number -lt 100 ]
then
echo “Numeric values is less then 100”
fi

and we have nested if statement to validate the sme numeric values.
nested if is nothing but we are using if statement inside of if statement.

#vi ifstat2.sh

#!/bin/bash
echo “Enter a numeric value”
read number
if [ $number -eq 100 ]
then
echo “Numeric value is 100”
else
if[ $number -gt 100 ]
then
echo “Numeric values is greater then 100”
else
echo “Numeric values is less then 100”
fi
fi

Leave a Reply

Your email address will not be published. Required fields are marked *