DSE-1: UNIX PROGRAMMING
UNIT-4
UNIX CONTROL STRUCTURES AND UTILITIES
Decision making in Shell Scripts
if statement
This block will process if specified condition is true.
Syntax:
if [ expression ]
then
statement
fi
if-else statement
If specified condition is not true in if part then else part will be execute.
Syntax:
if [ expression ]
then
statement1
else
statement2
fi
if..elif..else..fi statement (Else If ladder)
To use multiple conditions in one if-else block, then elif keyword is used in shell. If
expression1 is true then it executes statement 1 and 2, and this process continues. If none of the
condition is true then it processes else part.
Syntax
if [ expression1 ]
then
statement1
statement2
.
.
elif [ expression2 ]
then
statement3
statement4
.
.
else
statement5
fi
if..then..else..if..then..fi..fi..(Nested if)
Nested if-else block can be used when, one condition is satisfies then it again checks another
condition. In the syntax, if expression1 is false then it processes else part, and again
expression2 will be check.
Syntax:
if [ expression1 ]
then
statement1
statement2
.
else
if [ expression2 ]
then
statement3
.
fi
fi
switch statement
case statement works as a switch statement if specified value match with the pattern then it will
execute a block of that particular pattern
When a match is found all of the associated statements until the double semicolon (;;) is
executed.
A case will be terminated when the last command is executed.
If there is no match, the exit status of the case is zero.
Syntax:
case in
Pattern 1) Statement 1;;
Pattern n) Statement n;;
Esac
Example Programs
Example 1:
Implementing if statement
#Initializing two variables
a=10
b=20
#Check whether they are equal
if [ $a == $b ]
then
echo "a is equal to b"
fi
#Check whether they are not equal
if [ $a != $b ]
then
echo "a is not equal to b"
fi
Output
$bash -f main.sh
a is not equal to b
Example 2:
Implementing if.else statement
#Initializing two variables
a=20
b=20
if [ $a == $b ]
then
#If they are equal then print this
echo "a is equal to b"
else
#else print this
echo "a is not equal to b"
fi
Output
$bash -f main.sh
a is equal to b
Example 3:
Implementing switch statement
CARS="bmw"
#Pass the variable in string
case "$CARS" in
#case 1
"mercedes") echo "Headquarters - Affalterbach, Germany" ;;
#case 2
"audi") echo "Headquarters - Ingolstadt, Germany" ;;
#case 3
"bmw") echo "Headquarters - Chennai, Tamil Nadu, India" ;;
Esac
Output
$bash -f main.sh
Headquarters - Chennai, Tamil Nadu, India.
Looping Statements in Shell Scripting
There are total 3 looping statements which can be used in bash programming
1. while statement
2. for statement
3. until statement
To alter the flow of loop statements, two commands are used they are,
1. break
2. continue
Their descriptions and syntax are as follows:
while statement
Here command is evaluated and based on the result loop will executed, if command raise to
false then loop will be terminated
Syntax
while command
do
Statement to be executed
done
for statement
The for loop operate on lists of items. It repeats a set of commands for every item in a list.
Here var is the name of a variable and word1 to wordN are sequences of characters
separated by spaces (words). Each time the for loop executes, the value of the variable var
is set to the next word in the list of words, word1 to wordN.
Syntax
for var in word1 word2 ...wordn
do
Statement to be executed
done
until statement
The until loop is executed as many as times the condition/command evaluates to false. The
loop terminates when the condition/command becomes true.
Syntax
until command
do
Statement to be executed until command is true
done
Example Programs
Example 1:
Implementing for loop with break statement
#Start of for loop
for a in 1 2 3 4 5 6 7 8 9 10
do
# if a is equal to 5 break the loop
if [ $a == 5 ]
then
break
fi
# Print the value
echo "Iteration no $a"
done
Output
$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
Example 2:
Implementing for loop with continue statement
for a in 1 2 3 4 5 6 7 8 9 10
do
# if a = 5 then continue the loop and
# don't move to line 8
if [ $a == 5 ]
then
continue
fi
echo "Iteration no $a"
done
Output
$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
Iteration no 6
Iteration no 7
Iteration no 8
Iteration no 9
Iteration no 10
Example 3:
Implementing while loop
a=0
# -lt is less than operator
#Iterate the loop until a less than 10
while [ $a -lt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done
Output:
$bash -f main.sh
0
1
2
3
4
5
6
7
8
9
Example 4:
Implementing until loop
a=0
# -gt is greater than operator
#Iterate the loop until a is greater than 10
until [ $a -gt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done
Output:
$bash -f main.sh
0
1
2
3
4
5
6
7
8
9
10
Example 5:
Write a shell script to generate Fibonacci series up to n terms where the value of n is give
interactively at run time.
c=2
a=1
b=1
d=0
echo "enter the number of elements"
read n
echo "$a"
echo "$b"
while((c<n))
do
d=$((a+b))
echo "$d"
a=$b
b=$d
c=$((c+1))
done
Output:
enter the number of elements
6
1
1
2
3
5
8
test command:
A test command is a command that is used to test the validity of a command. It checks whether
the command/expression is true or false.
Syntax: test [ expression ]
Test [“var1” operator “var2”]
1)Numeric Comparisions
Example-1
#two numbers are equal or not.
a=20
b=20
if test “$a” –eq “$b”
then
echo “a is equal to b”
else
echo “a is not equal to b”
fi
output:
a is equal to b
2)string comparisons
a=”hello”
b=”hello”
if test “$a” = “$b”
then
echo “a is equal to b”
else
echo “a is not equal to b”
fi
output:
a is equal to b
Comparison operators used in test command for string:
equal to (=)
not equal (!=)
-n string (checks whether the string is empty or not)
Comparison operators used in test command for numbers:
equal to (-eq)
not equal to (-ne)
greater than (-gt)
less than (-le)
greater than equal to (-ge)
less than ewual to (-le)
Functions:
Functions enable you to break down the overall functionality of a script into smaller, logical
subsections, which can then be called upon to perform their individual tasks when needed.
Using functions to perform repetitive tasks is an excellent way to create code reuse. This is an
important part of modern object-oriented programming principles.
Creating Functions
To declare a function, simply use the following syntax −
function_name () {
list of commands
}
The name of your function is function_name, and that's what you will use to call it from
elsewhere in your scripts. The function name must be followed by parentheses, followed by a
list of commands enclosed within braces.
Example
Following example shows the use of function −
Live Demo
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World"
}
# Invoke your function
Hello
Upon execution, you will receive the following output −
$./test.sh
Hello World
Pass Parameters to a Function
You can define a function that will accept parameters while calling the function. These
parameters would be represented by $1, $2 and so on.
Following is an example where we pass two parameters Zara and Ali and then we capture and
print these parameters in the function.
Live Demo
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World $1 $2"
}
# Invoke your function
Hello Zara Ali
Upon execution, you will receive the following result −
$./test.sh
Hello World Zara Ali
Returning Values from Functions
If you execute an exit command from inside a function, its effect is not only to terminate
execution of the function but also of the shell program that called the function.
If you instead want to just terminate execution of the function, then there is way to come out of
a defined function.
Based on the situation you can return any value from your function using the return command
whose syntax is as follows −
return code
Here code can be anything you choose here, but obviously you should choose something that is
meaningful or useful in the context of your script as a whole.
Example
Following function returns a value 10 –
Live Demo
#!/bin/sh
# Define your function here
Hello () {
echo "Hello World $1 $2"
return 10
}
# Invoke your function
Hello Zara Ali
# Capture value returnd by last command
ret=$?
echo "Return value is $ret"
Upon execution, you will receive the following result −
$./test.sh
Hello World Zara Ali
Return value is 10
Nested Functions
One of the more interesting features of functions is that they can call themselves and also other
functions. A function that calls itself is known as a recursive function.
Following example demonstrates nesting of two functions −
Live Demo
#!/bin/sh
# Calling one function from another
number_one () {
echo "This is the first function speaking..."
number_two
}
number_two () {
echo "This is now the second function speaking..."
}
# Calling function one.
number_one
Upon execution, you will receive the following result −
This is the first function speaking...
This is now the second function speaking..
Positional Parameter in Shell Script:
A shell script has parameters. These parameters start from $1 to $9. When we pass arguments
into the command line interface, a positional parameter is assigned to these arguments through
the shell.
The first argument is assigned as $1, second argument is assigned as $2 and so on….
If there are more than 9 arguments, then tenth or onwards arguments can’t be assigned as $10 or
$11.
Parameters Description
$1 The first arguments sent to the scripts/programs.
$2 The second arguments sent to the scripts/programs
${10}-${n} Represent positional parameters for arguments after nine.
$? The return value of a command is stored in the $? Variable. The return value is
called exit status.
$# It refers to the value of the total number of command line arguments passed.
$$ PID of the script
Types of functions:
1) The functions that terminate the shell using the exit keyword.
is_odd()
{
x=$1
if [ $((x % 2))== 0 ]
then
echo “invalid input”
exit 1
else
echo “Number is odd”
fi
}
is_odd 24
Output:
Invalid input
2)The functions that alter the value of a variable.
a=1 #global declaration
increment()
{
a=$((a+1))
return
}
increment
echo “$a”
Output:
2
3)The functions that echo output to the standard output
welcome()
{
echo “Hello world”
return
}
welcome
Output:
Hello World
4)The functions that return value to the caller. The return keyword is used by the functions
for this purpose.
# Define your function here
Hello () {
echo "Hello World $1 $2"
return 10
}
# Invoke your function
Hello Zara Ali
# Capture value returnd by last command
ret=$?
echo "Return value is $ret"
Function Call from Prompt
You can put definitions for commonly used functions inside your .profile. These definitions will
be available whenever you log in and you can use them at the command prompt.
Alternatively, you can group the definitions in a file, say test.sh, and then execute the file in the
current shell by typing −
$. test.sh
This has the effect of causing functions defined inside test.sh to be read and defined to the
current shell as follows −
$ number_one
This is the first function speaking...
This is now the second function speaking...
$
To remove the definition of a function from the shell, use the unset command with the .f option.
This command is also used to remove the definition of a variable to the shell.
$ unset -f function_name
Pattern matching utility (grep):
The grep filter searches a file for a particular pattern of characters, and displays all lines that
contain that pattern. The pattern that is searched in the file is referred to as the regular
expression (grep stands for global search for regular expression and print out).
Syntax: grep [options] pattern [files]
Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.
-A n : Prints searched line and n lines after the result.
-B n : Prints searched line and n line before the result.
-C n : Prints searched line and n lines after before the result.
Sample Commands
Consider the below file as an input.
$cat > myfile.txt
unix is great os. unix is opensource. unix is free os.
learn operating system.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
1. Case insensitive search : The -i option enables to search for a string case insensitively in
the given file. It matches the words like “UNIX”, “Unix”, “unix”.
$grep -i "UNix" myfile.txt
Output:
unix is great os. unix is opensource. unix is free os.
Unix linux which one you choose.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
2. Displaying the count of number of matches : We can find the number of lines that
matches the given string/pattern
$grep -c "unix" myfile.txt
Output:
2
3. Display the file names that matches the pattern : We can just display the files that
contains the given string/pattern.
$grep -l "unix" *
or
$grep -l "unix" f1.txt f2.txt f3.xt f4.txt
Output:
Myfile.txt
4. Checking for the whole words in a file : By default, grep matches the given string/pattern
even if it is found as a substring in a file. The -w option to grep makes it match only the whole
words.
$ grep -w "unix" myfile.txt
Output:
unix is great os. unix is opensource. unix is free os.
uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
5. Displaying only the matched pattern : By default, grep displays the entire line which has
the matched string. We can make the grep to display only the matched string by using the -o
option.
$ grep -o "unix" myfile.txt
Output:
unix
unix
unix
unix
unix
unix
6. Show line number while displaying the output using grep -n : To show the line number
of file with the line matched.
$ grep -n "unix" myfile.txt
Output:
1:unix is great os. unix is opensource. unix is free os.
4:uNix is easy to learn.unix is a multiuser os.Learn unix .unix is a powerful.
7. Inverting the pattern match : You can display the lines that are not matched with the
specified search string pattern using the -v option.
$ grep -v "unix" myfile.txt
Output:
learn operating system.
Unix linux which one you choose.
8. Matching the lines that start with a string : The ^ regular expression pattern specifies the
start of a line. This can be used in grep to match the lines which start with the given string or
pattern.
$ grep "^unix" myfile.txt
Output:
unix is great os. unix is opensource. unix is free os.
9. Matching the lines that end with a string : The $ regular expression pattern specifies the
end of a line. This can be used in grep to match the lines which end with the given string or
pattern.
$ grep "os$" myfile.txt
10.Specifies expression with -e option. Can use multiple times :
$grep –e "Agarwal" –e "Aggarwal" –e "Agrawal" geekfile.txt
11. -f file option Takes patterns from file, one per line.
$cat pattern.txt
Agarwal
Aggarwal
Agrawal
$grep –f pattern.txt geekfile.txt
12. Print n specific lines from a file: -A prints the searched line and n lines after the result, -
B prints the searched line and n lines before the result, and -C prints the searched line and n
lines after and before the result.
Syntax:
$grep -A[NumberOfLines(n)] [search] [file]
$grep -B[NumberOfLines(n)] [search] [file]
$grep -C[NumberOfLines(n)] [search] [file]
Example:
$grep -A1 learn geekfile.txt
Output:
learn operating system.
Unix linux which one you choose.