How to use if condition in shell scripting
How to use if condition in Shell scripting?
In this article, we will see shell decision-making in Unix. While writing a shell script, there may be a situation when you need to adopt one path out of the given paths. So you need to make use of conditional statements that allow your program to make correct decisions and perform the right actions.
Unix Shell supports conditional statements that are used to perform different actions based on different conditions. We will now understand decision-making statements here −
if...else statement
If else statements are useful decision-making statements which can be used to select an option from a given set of options.
Unix Shell supports following forms of if…else statement −
if...fi statement
if...else...fi statement
if...elif...else...fi statement
#! /bin/bash
#To setup if statement and condition
if [ condition ]
then
statement
fi
count=10
if (( $count > 11 ))
then
echo "condition is true"
else
echo "condition is false"
fi
word=a
if [[ $word < "b" ]]
then
echo "condition is true"
else
echo "condition is false"
fi
word=a
if [[ $word == "b" ]]
then
echo "condition is true"
elif [[ $word != "a" ]]
then
echo "condition is false"
else
echo "condition will be true"
fi
#To check file and directory is exist or not such as -e file, -f file, -d directory,-b blog file such as video, -c charectpr, -s size, -l, -r ,-w, -x
echo -e "Enter the name of the file : \c"
read file_name
if [ -s $file_name ]
then
echo "$file_name found"
else
echo "$file_name not found"
fi
#! /bin/bash
#it is logical and value where both condition should be correct if any one condition will be wrong so get false outcome
age=60
if [ "$age" -gt 18 ] && [ "$age" -lt 70 ]
then
echo "valid age"
else
echo "unvalid age"
fi
age=60
if [ "$age" -gt 18 ] && [ "$age" -lt 59 ]
then
echo "valid age"
else
echo "unvalid age"
fi
#It is logical or value where anyone or both condition should be correct
age=60
if [ "$age" -gt 18 ] || [ "$age" -lt 59 ]
then
echo "valid age"
else
echo "unvalid age"
fi
people=100
if [ "$people" -lt 50 ] && [ "$people" -gt 51 ]
then
echo "total number of people correct"
else
echo "total number of people not correct"
fi
people=100
if [ "$people" -lt 101 ] && [ "$people" -gt 51 ]
then
echo "total number of people correct"
else
echo "total number of people not correct"
fi
people=100
if [ "$people" -lt 100 -o "$people" -gt 51 ]
then
echo "total number of people correct"
else
echo "total number of people not correct"
fi
0 comments
Please leave your comments...... Thanks