KSH IF Command Conditional Scripting Examples

by on July 2, 2007 · 0 comments· LAST UPDATED November 18, 2013

in , ,

How do I use if command with KSH to make decisions on Unix like operating systems?

KSH offers program flow control using if conditional command. if statement runs a set of command if some condition is true. For example, if directory /backup does not exists, create a new one so that your shell script can make backup to /backup directory.
Tutorial details
DifficultyEasy (rss)
Root privilegesNo
Requirementsksh
Estimated completion time10m
if statement has else part and it is get executed when condition is not satisfied or set to false state. This is also know as branching in ksh script.

KSH if statement syntax

The syntax is as follows:

 
     if [[ condition ]]; then
         // Condition satisfied and run commands between if..fi
     fi
 

OR

    if [ condition ] ; then
    	// Condition satisfied and run this command
    else
    	// Condition NOT satisfied and run this command
    fi

OR

 
if [[ condition1 ]];then
   // Condition1 satisfied and run this command
elif [[ condition2 ]];then
   // Condition2 satisfied and run this command
else
   // Both Condition1 and Condition2 are false, so run this command
fi
 

Examples

IF the variable $x is greater to 0, THEN print out a message. Otherwise (else), print out a different message. Following shell script to read 2 numbers and find the greaters of the two:

#!/bin/ksh
x=51
y=10
echo "Value of x = $x and y = $y."
echo "The greaters of the two"
if [ $x -ge $y ];
then
        echo "x = $x "
else
        echo "y = $y"
fi

Save and close the file. Run it as follows:
$ chmod +x script-name
$ ./script-name

Sample outputs:

Value of x = 51 and y = 10.
The greaters of the two
x = 51 

Find out if file /etc/passwd exists or not:

#!/bin/ksh
FILE=/etc/passwd
DIR=/tmp/foo
# ! means not 
# if file does exists 
if [ ! -f $FILE ];
then
	echo "Error $FILE does not exists!"
else
	echo "$FILE found!"
fi
# if dir does not exists
if [ ! -d $DIR ];
then
	echo "Error directory $DIR does not exists!"
else
	echo "$DIR directory found!"
fi

The -d option check for $DIR and make sure it is a directory. The -f option check for $FILE and make sure it is a regular file using conditional if command. The following script use if then elif then else fi syntax to display your OS name:

#!/bin/ksh
# find-os.ksh : Guess your OS name.
# get os type
os="$(uname)"
 
# make a decision 
if [[ $os = "Linux" ]];
then
	print "You are using Linux"
elif [[ $os = "Darwin" ]];
then
	print "You are using OS X"
else
 	print "You are using Unix like os"
fi
 

Run it as follows:
$ chmod +x find-os.ksh
$ ./find-os.ksh

Sample outputs:

You are using OS X

See ksh(1) man page for more information.

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 0 comments… add one now }

Leave a Comment

Tagged as: , , , , , , , , , , , , ,

Previous Faq:

Next Faq: