These are the statements which redirect the logic of a script on the basis of some condition. If If the condition is satisfied then if blo...
These are the statements which redirect the logic of a script on the basis of some condition.
If
If the condition is satisfied then if block gets executed otherwise if statements will not execute
Example
Find the total free space on the root directory and if it is less than 20% (free/total *100) then send a notification message then "Alert! disk space is too low"
usedspace=`df / | awk '{print $5}' | sed '1d' | cut -c1`
threshold=2
if [ $usedspace -gt $threshold ]
then
echo "Alert ! used space $usedspace which is more than $threshold"
fi
Example with command-line value for the threshold
usedspace=`df / | awk '{print $5}' | sed '1d' | cut -c1`
threshold=$1
if [ $usedspace -gt $threshold ]
then
echo "Alert ! used space $usedspace which is more than $threshold"
fi
Execute
./alert.sh 80
If - else
usedspace=`df / | awk '{print $5}' | sed '1d' | cut -c1`
threshold=$1
if [ $usedspace -gt $threshold ]
then
echo "Alert ! used space $usedspace which is more than $threshold"
else
echo "You have sufficient free space :)"
fi
Execute
./alert.sh 80
If -elif
For multiple if conditions
Example
Perform certain operation on apache service
status=`systemctl status apache2 | grep "active (running)" | wc -l`
if [ $# -lt 1 ]
then
var1="restart"
echo "No commandline argument is passed so default functionality is restarted"
else
var1="$1"
fi
echo "-----------Checking Apache Status------------"
if [ $status -ge 1 ] && [ $var1 == 'stop' ]
then
echo "apache is running now it is getting stopped"
systemctl stop apache2
echo "apache is in stopped mode"
elif [ $status -ge 1 ] && [ $var1 == 'restart' ]
then
echo "apache is running but the request is to restart it so restarting the apache"
systemctl restart apache2
echo "apache is in started mode"
elif [ $status -lt 1 ] && [ $var1 == 'restart' ]
then
echo "current status of apache is in stopped mode so as per request restarting the apache"
systemctl restart apache2
echo "apache is in started mode"
fi
echo "-------------Apache Operations are done---------"
Execute
./apachestatus.sh
output
No commandline argument is passed so default functionality is restarted
-----------Checking Apache Status------------
apache is running but the request is to restart it so restarting the apache
apache is in started mode
-------------Apache Operations are done---------
Execute
./apachestatus.sh stop
output
-----------Checking Apache Status------------
apache is running now it is getting stopped
apache is in stopped mode
-------------Apache Operations are done---------
case..esac
COMMENTS