Skip to main content

Flow Control in shell script - if and case statements


Shell script usualyl 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

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 syntaxs:
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: Biggest of 2 numbers ( using simple if)
echo "Enter two numbers..line by line."
read a
read b
if [ $a -gt $b ]
then
echo "$a is bigger"
else
echo "$b is bigger"
fi
Example: Biggest of 3 numbers ( using if elif)
echo "Enter three numbers in single line seperate with space"
read a b c
if [ $a -gt $b ]
then
if [ $a -gt $c ]
then
echo "$a is bigger"
fi
elif [ $b -gt $c ]
then
echo "$b is bigger"
else
echo "$c is bigger"
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 commandN. 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

KTU-FOSS LAB Solutions

Write shell scripts to show the following  ( you can write menu driven programs)
 Currently logged user and his logname ( logname)  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 cek....where cek 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 Processor core ( nproc)  Show memory information       Memory details ( cat /proc/meminfo | more )       Display file system disk usage ( d…

Important Directories and Files

Important Directories
/bin                            holds the “essential” Linux commands and utilities /boot                          holds files required for boot process (kernel, vmlinuz, grub) /dev                            holds device files (hard drive, USB, CD-ROM, etc.) /etc                             holds system configuration files /etc/init.d                    holds scripts to start/stop network services /etc/rc.d                     holds system startup/shutdown scripts /etc/X11                      holds configuration files for X-windows /home                        holds user home directories (except for the root account) /lib                               holds system/shared library files /lost+found                holds files restored after system crash /mnt                            used as temporary mount point for CD-ROM, floppy, etc. /opt                              typically where large software applications are installed /proc                           holds kerne…

ER Diagrams to Table

REDUCING E-R DIAGRAM TO TABLE - A database which conforms to an E R diagram can be represented by collection of tables .For each entity set and for each relationship set in the database, we will create unique tables, which is assigned the name of the corresponding entity set or relationship sets . Each table has a no. of columns which have unique names. Each row in the table corresponds to an entity or a relationship.

REPRESENTATION OF STRONG ENTITY SET -Let E be a strong entity set with descriptive attributes a1, a2....aN . We represent this entity by table called E with N distinct columns, each of which corresponds to one of the attributes of E.

REPRESENTATION OF RELATIONSHIP SET - Let R be a relation ship set involving entity set E1,E2....En Let attribute(R) consists of 'm' attributes We can represent this relation ship set by a table called R with m distinct columns, each of which corresponds to one of the attributes in attribute (R) plus the primary key of E1..En.

REPRESENTI…