Skip to main content

Flow Control in shell script - if and case statements


Shell script usually consist of sequence of commands that starts at the first line and continues line by line until it reaches the end. Most programs do much more than this. They make decisions and perform different actions depending on conditions.
The shell provides several commands that we can use to control the flow of execution in our program. In this lesson, we will look at the following: 
test
if
case
exit
 
test
The test command is used most often with the if command to perform true/false decisions. The command is unusual in that it has two different syntactic forms: # First form
test expression
# Second form
[ expression ]

The test command works simply. If the given expression is true, test exits with a status of zero; otherwise it exits with a status of 1.
Common numerical test conditions
-gt   Greater than
-lt    Less than
-ge  Greater than or equal to
-le    Less than or equal to
-eq   Equal to
-ne   Not equal to

-a AND
-o OR

Files and strings can also be tested
Expression Description
-d file True if file is a directory.
-e file True if file exists.
-f file True if file exists and is a regular file.
-L file True if file is a symbolic link.
-r file True if file is a file readable by you.
-w file True if file is a file writable by you.
-x file True if file is a file executable by you.
file1 -nt file2 True if file1 is newer than (according to modification time) file2
file1 -ot file2 True if file1 is older than file2
-z string True if string is empty.
-n string True if string is not empty.
string1 = string2 True if string1 equals string2.
string1 != string2 True if string1 does not equal string2.

if

The first command we will look at is if. The if command is fairly simple on the surface; it makes a decision based on the exit status of a command. The if command's syntax looks like this:
The if statement has the following syntax:

simple if
if [condition ]
then
#commands
fi

if else statement
if [ condition ]
then
#commands
else
#commands
fi

if elif statement
if [ condition ]
then
commands
elif [ condition ]
#commands
else
#commands
fi
multiple conditions are specified with AND ( -a) and OR(-o)

Example: Even or odd ( using simple if)

echo "Enter a number"
read n
r=`expr $n % 2`
if [ $r -eq 0 ]
then
    echo "$n is even"
else
    echo "$n is odd"
fi

Example: Biggest of 2 numbers ( using if elif)

echo "Enter two numbers in single line separate with space"
read a b
if [ $a -gt $b ]
then
    echo "$a is bigger"
elif [ $b -gt $a ]
then
    echo "$b is bigger"
else
    echo "equal"
fi
 
Biggest of 3 numbers using and (-a) operator
echo "enter three numbers.."
read a b c
if [ $a -gt $b -a $a -gt $c ]
then
    echo "$a is big"
elif [ $b -gt $a -a $b -gt $c ]
then
    echo "$b is big"
else
    echo "$c is big"
fi

Case statement
The case statement is good alternative to multilevel if-then-else-fi statement. It enable you to match several values against one variable. It is easier to read and write. 
Syntax
The syntax is as follows:

case $variable-name in
pattern1)
command1
...
....
commandN
;;
pattern2)
command1
...
....
commandN
;;
patternN)
command1
...
....
commandN
;;
*)
esac
OR
case $variable-name in
pattern1|pattern2|pattern3)
command1
...
....
commandN
;;
pattern4|pattern5|pattern6)
command1
...
....
commandN
;;
pattern7|pattern8|patternN)
command1
...
....
commandN
;;
*)
esac

The case statement allows you to easily check pattern (conditions) and then process a command-line if that condition evaluates to true.

In other words the $variable-name is compared against the patterns until a match is found.

*) acts as default and it is executed if no match is found.

The pattern can include wildcards.

You must include ;; at the end of each command. The shell executes all the statements up to the two semicolons that are next to each other.

The esac is always required to indicate end of case statement.

Example:Read a day number and print the day
echo "Enter the day number.."
read d
case $d in
1) echo "sunday";;
2)echo "monday";;
3)echo "tuesday";;
4)echo "wednesday";;
5)echo "thursday";;
6)echo "friday";;
7)echo "saturday";;
*)echo "Invalid choice..enter 1-7";;
esac

Example:Enter a char and check for vowel
echo "Enter a character.."
read c
case $c in
    a|A|e|E|i|I|o|O|u|U) echo "vowel";;
    *)echo "not a vowel character";;
esac

exit
In order to be good script writers, we must set the exit status when our scripts finish. To do this, use the exit command. The exit command causes the script to terminate immediately and set the exit status to whatever value is given as an argument. 
For example:
exit 0 exits your script and sets the exit status to 0 (success), whereas
exit 1 exits your script and sets the exit status to 1 (failure).

Comments

Popular posts from this blog

Introduction to Data Structures

Visit My Data Structure Blog for Programs... It is important for every Computer Science student to understand the concept of Information and how it is organized or how it can be utilized. If we arrange some data in an appropriate sequence, then it forms a Structure and gives us a meaning. This meaning is called Information . A data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently. Data may be organized in many different ways. The logical model of a particular organization of data in a computer is called data structure. The choice of the model based on two considerations. It should be reflect the data in the real world. It should be simple that one can effectively process the data when necessary. E.g. Array, linked list, stack, queue, tree, graph Data structure can be classified into two: Linear: A data structure is said to be linear if its elements form a sequence E.g. Array, linked list, stack, queue Non-Linear: A dat

Basic Linux Commands For Beginner's

Basic Linux Commands for Beginners Linux is an Operating System’s Kernel. You might have heard of UNIX. Well, Linux is a UNIX clone. But it was actually created by Linus Torvalds from Scratch. Linux is free and open-source, that means that you can simply change anything in Linux and redistribute it in your own name! There are several Linux Distributions, commonly called “distros”. A few of them are: Mint Ubuntu Linux Red Hat Enterprise Linux Debian Fedora Kali Linux is Mainly used in Servers. About 90% of the Internet is powered by Linux Servers. This is because Linux is fast, secure, and free! The main problem of using Windows Servers are their cost. This is solved by using Linux Servers. Forgot to mention, the OS that runs in about 80% of the Smartphones in the World, Android, is also made from the Linux Kernel. Yes, Linux is amazing! A simple example of its security is that most of the viruses in the world run on Windows, but not on Linux

KTU-FOSS LAB Solutions

Write shell scripts to show the following  ( you can write menu driven programs)  Currently logged user and his logname   ( logname, id -un, echo $USER)  Your current shell ( echo $SHELL)  Your home directory ( echo $HOME)  Your operating system type (echo $OSTYPE)  Your current path setting ( echo $PATH)  Your current working directory ( echo $PWD )  Show Currently logged  users ( w or who -H)      Show only the user name of logged users in the host ( users)      Details of last login ( last mec  ;where mec is the user id )  About your OS and version, release number, kernel version                                                 ( uname -a or  cat  /proc/version)  Show all available shells ( cat /etc/shells )  Show mouse settings (cat  /sys/class/input/mouse*/device/name )  Show computer CPU information       CPU details      ( cat /proc/cpuinfo | more )       Show information on  CPU architecture ( lscpu)       Number of Processo