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

Writing a Bash Shell Script

What Are Shell Scripts? In the simplest terms, a shell script is a file containing a series of commands. The shell reads this file and carries out the commands as though they have been entered directly on the command line. The shell is somewhat unique, in that it is both a powerful command line interface to the system and a scripting language interpreter. As we will see, most of the things that can be done on the command line can be done in scripts, and most of the things that can be done in scripts can be done on the command line. Writing Your First Script And Getting It To Work To successfully write a shell script, you have to do three things: Write a script Give the shell permission to execute it Put it somewhere the shell can find it Writing A Script A shell script is a file that contains ASCII text. To create a shell script, you use a text editor . A text editor is a program, like a word processor, that reads and writes ASCII text files. There are...

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...

Shell

Definition of the Shell Shell is an interactive environment which provides an interface to an Operating System. It gathers input from user and execute the commands. Bourne shell(sh)- 1977 The Bourne shell was introduced. The Bourne shell(sh), by Stephen Bourne at AT&T Bell Labs for V7 UNIX, remains a useful shell today (in some cases, as the default root shell). The Bourne shell was developed after working on an ALGOL68 compiler, so its grammar is more along the lines of Algorithmic Language (ALGOL) than other shells. The source code was developed in C. The Bourne shell served two primary goals: Executing UNIX/Linux commands for the operating system,i.e, command line interpreter Writing reusable scripts that could be invoked through the shell,i.e, scripting In addition to replacing the Thompson shell, the Bourne shell offered many other advantages over its predecessors such as control flows, loops, and variables into scripts, providing a more functional language to...