The if statement
There are three shells available in shell command. All the three shells support and maintain nested if...then...else statements. These statements give a way of performing complicated conditional tests in shell programs.
Syntax
if [ expression ]
then commands
elif [ expression ]
then commands
else commands
fi
Practice 1
The given shell program will search if the '.profile' file is present in the current directory
# vi checkprofile
echo -e "Enter the filename to search :\\c"
read fname
if [ -f $fname ]
then
echo "An $fname file is available within current directory"
else
echo "Could not find the .profile file"
fi
# sh checkprofile
The given program will check for the file. Profile in the current directory by using the test option -f.it will show the message there is if the file is found. Profile file in the current directory otherwise it will show the message could not search the .profile file.
Practice 2
The given shell program will find of the 3 numbers.
# vi greatnum
echo -e "Enter the value of a, b and c:"
read a read b read c
if [ $a -gt $b -a $a -gt $c ]
then
echo $a is greater than $b and $c elif [ $b -gt $c ]
then
echo $b is greater than $a and $c else
echo $c is greater than $a and $b fi
# sh greatnum
Enter the value for a, b and c:
12
34
56
56 is greater than 12 and 34