KSH IF Command Conditional Scripting Examples

by Vivek Gite · 0 comments

This entry is part 3 of 3 in the series UNIX Korn Shell Scripting

How do I use if command under KSH to make decisions?

KSH offers program flow control using if conditional command. if command 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.

KSH IF Syntax

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

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=5
y=10
if [ $x -ge $y ];
then
	echo "x = $x "
else
	echo "y = $y"
fi

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.

Series Navigation«Korn Shell Variables

Featured Articles:

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 0 comments… add one now }

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous FAQ:

Next FAQ: