If..else..fi

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← if structures to execute code based on a conditionHomeNested ifs →

if..else..fi allows to make choice based on the success or failure of a command. For example, find out if file exists (true condition) or not (false condition) and take action based on a condition result.

if..then..else Syntax

           if command
           then
                       command executed successfully
                       execute all commands up to else statement
                       or to fi if there is no else statement

           else
                       command failed so
                       execute all commands up to fi
           fi

OR

           if test var -eq val
           then
                       command executed successfully
                       execute all commands up to else statement
                       or to fi if there is no else statement

           else
                       if command failed then
                       execute all commands up to fi
           fi

OR

           if [ condition ]
           then
                       if given condition true
                       execute all commands up to else statement
                       or to fi if there is no else statement

           else
                       if given condition false 
                       execute all commands up to fi
           fi

Make sure you always end the construct with fi.

if/then/else Example

Update verify.sh as follows

##!/bin/bash
read -p "Enter a password" pass
if test "$pass" = "jerry"
then
     echo "Password verified."
else
     echo "Access denied."	
fi

Save and close the file. Run it as follows:

./verify.sh

You have updated verify.sh and added an else statement to existing if command to create if..else..fi structure. If $pass (i.e. password) is equal to "jerry", then "Password verified." is displayed. However, with else statement, the script can display "Access denied." message on screen. This ensures that your script will always execute one of the code block as follows:

if command is successful
then
  print "Password verified message."
else    # if condition is false
  print "Access denied message."
fi

Number Testing Script

Create a shell script called testnum.sh:

#!/bin/bash
read -p "Enter number : " n
if test $n -ge 0
then
	echo "$n is positive number."
else
	echo "$n number is negative number."
fi

Save and close the file. Run it as follows:

chmod +x testnum.sh
./testnum.sh

Putting It All Together

The following script (chk_hardware.sh) use mcelog command on x86-64 machines running a 64-bit Linux kernel. It will find out hardware error such as RAM or CPU and send an e-mail to server administrator. This is useful for predicting server hardware failure before actual server crash. This script demonstrates:

  • Script comments
  • Shell script variable
  • if..else..fi command
  • Sending an e-mail from the script
#!/bin/bash
# Purpose: Detecting Hardware Errors
# Author: Vivek Gite <vivek@nixcraft.com>
# Note : The script must run as a cron-job.
# Last updated on : 28-Aug-2007
# -----------------------------------------------
 
# Store path to commands
LOGGER=/usr/bin/logger
FILE=/var/log/mcelog
 
# Store email settings
AEMAIL="vivek@nixcraft.net.in"
ASUB="H/W Error - $(hostname)"
AMESS="Warning - Hardware errors found on $(hostname) @ $(date). See log file for the details /var/log/mcelog."
OK_MESS="OK: NO Hardware Error Found."
WARN_MESS="ERROR: Hardware Error Found."
 
 
# Check if $FILE exists or not
if test ! -f "$FILE" 
then   
	echo "Error - $FILE not found or mcelog is not configured for 64 bit Linux systems."
	exit 1
fi
 
# okay search for errors in file
error_log=$(grep -c -i "hardware error" $FILE)
 
# error found or not?
if [ $error_log -gt 0 ]
then    # yes error(s) found, let send an email
	echo "$AMESS" | email -s "$ASUB" $AEMAIL
else    # naa, everything looks okay
	echo "$OK_MESS"
fi
← if structures to execute code based on a conditionHomeNested ifs →