Tuesday, March 24, 2009

If/Else

Remember that the spacing is very important in the if statement.
Notice that the termination of the if statement is fi.
You can also replace the "==" with "!=" to test if the variables are NOT equal.

Comparisons:
-eq : equal to
-ne : not equal to
-lt : less than
-le : less than or equal to
-gt : greater than
-ge : greater than or equal to

File Operations:
-s : file exists and is not empty
-f : file exists and is not a directory
-d : directory exists
-x : file is executable
-w : file is writable
-r : file is readable

Script 1:

First, to write age to a file, named "username_DAT".

======================================
#!/bin/sh

# Prompt for a user name...
echo "Please enter your name:"
read USERNAME

# Check for the file.
if [ -s ${USERNAME}_DAT ]; then
# Read the age from the file.
AGE=`cat ${USERNAME}_DAT`
echo "You are $AGE years old!"
else
# Ask the user for his/her age
echo "How old are you?"
read AGE

if [ "$AGE" -le 2 ]; then
echo "You are too young!"
else
if [ "$AGE" -ge 100 ]; then
echo "You are too old!"
else
# Write the age to a new file.
echo $AGE > ${USERNAME}_DAT
fi
fi
fi
======================================

You can test multiple expressions at once by using the (or) operator or the && (and) operator.
The structure of elif is the same as the structure of if

Script 2:

======================================
#!/bin/sh

# Prompt for a user name...
echo "Please enter your age:"
read AGE

if [ "$AGE" -lt 20 ] [ "$AGE" -ge 50 ]; then
echo "Sorry, you are out of the age range."
elif [ "$AGE" -ge 20 ] && [ "$AGE" -lt 30 ]; then
echo "You are in your 20s"
elif [ "$AGE" -ge 30 ] && [ "$AGE" -lt 40 ]; then
echo "You are in your 30s"
elif [ "$AGE" -ge 40 ] && [ "$AGE" -lt 50 ]; then
echo "You are in your 40s"
fi
======================================