0% found this document useful (0 votes)
2 views26 pages

12.essential Shell Programming

Uploaded by

sushilkmr86
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views26 pages

12.essential Shell Programming

Uploaded by

sushilkmr86
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT

12 Essential Shell Programming

Names of Sub-Units

Shell Variables, Environment Variables, Shell Scripts, Read: Making Scripts Interactive, Using Command
Line Arguments, Exit and Exit status of Command, The Logical Operators and Conditional Execution,
Condition Control Structures & Looping Control Structure, Handling Using the expr command, Looping
Using the while Loop, Looping with a List Using the for Loop, Manipulating the Positional Parameters
using set and shift Command, Interrupting a Program Using the trap Command, Debugging Shell
Scripts with the set –x Command

Overview
In this unit, you will learn about Shell Variables, Environment Variables, Shell Scripts, Read: Making
Scripts Interactive, Using Command Line Arguments as well as Exit and Exit status of Command. Also,
the unit describes the Logical Operators and Conditional Execution, Condition Control Structures &
Looping Control Structure, Handling Using the expr command, Looping Using the while Loop and
Looping with a List Using the for Loop. Further, it covers the concept of manipulating the Positional
Parameters Using set and shift Command and interrupting a Program Using the trap Command.
Towards the end, you will read about debugging Shell Scripts with the set –x Command.

Learning Objectives

In this unit, you will learn to:


 Explain shell programmes and basic shell commands
 Describe the concept of logical operators
 Define the condition and looping control structure
 Discuss the process of manipulating the positional parameters using set and shift command
 Summarise the debugging shell scripts with the set –x command.
JGI JAIN
DEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

Learning Outcomes

At the end of this unit, you would:


 Outline the concept of shell variables, environment variables and shell scripts
 Analyse the concept of logical operators
 Evaluate the use of condition and looping control structure
 Understand manipulating the positional parameters using set and shift command
 Examine the debugging shell scripts with the set –x command

Pre-Unit Preparatory Material

 [Link]

12.1 INTRODUCTION
A shell program, often known as a shell script, is a program made up entirely of shell commands. Every
time a shell program is executed, it is interpreted. This means that the shell processes (i.e., executes)
each command one line at a time. This differs from languages such as C or C++, which are completely
converted into binary images by compiler software. A shell program might be basic, including only a
few shell commands, or complicated, containing thousands2 of shell instructions. The programmer is in
charge of the shell program’s complexity. In general, a shell programmer may be described as follows:
 Shell programmes, such as any other file, have permission modes and must have the right
permissions configured to run. As other programming languages, the shell language supports input
and output, repetition, logical decision making, file creation and deletion and system calls.
 Shell programmes can be written in any format as long as each shell command’s syntax is valid.
This allows for the usage of blank lines, indentation and a lot of white spaces.

An interface to the Unix system is provided via a Shell. It takes your input and uses it to run applications.
It shows the result of a programme once it has completed its execution. The shell is a command,
programme and shell script execution environment. Shells come in a variety of flavours, similar to
how operating systems come in a variety of flavours. Each shell type has its own set of commands and
functionalities that are well-known.

12.2 SHELL VARIABLES


A variable is a character string that has a value attached to it. A number, text, filename, device, or any
other sort of data might be assigned as the value.
A variable is simply a reference to the real data. Variables can be created, assigned and deleted via the
shell.

12.2.1 Variable Names


Only letters (a to z or A to Z), integers (0 to 9) or the underscore character (_) can be used in a variable’s
name.

2
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

Unix shell variables are named in UPPERCASE as a matter of tradition.


The following examples are valid variable names:
_ALI
TOKEN_A
VAR_1
VAR_2
Following are the examples of invalid variable names:
2_VAR
-VARIABLE
VAR1-VAR2
VAR_A!
Other characters, such as!, *, or - are not allowed since they have a particular meaning for the shell.

12.2.2 Defining Variables


Variables are defined as follows:
variable_name=variable_value
For example,
NAME="Zara Ali"
The variable NAME is defined in the preceding example, and the value “Zara Ali” is assigned to it. Scalar
variables are variables of this type. At any given moment, a scalar variable can only retain one value.
For example,
VAR1="Zara Ali"
VAR2=100

12.2.3 Accessing Values


Prefix a variable’s name with the dollar symbol ($) to access the value stored in it. The following script,
for example, will retrieve the value of the declared variable NAME and output it to STDOUT.
#!/bin/sh
NAME="Zara Ali"
echo $NAME
The above script will produce the following value:
Zara Ali

12.2.4 Read-only Variables


The read-only command in Shell can be used to mark variables as read-only. A variable’s value cannot
be modified after it has been designated as read only.
For example, the following script generates an error while trying to change the value of NAME –
#!/bin/sh
NAME="Zara Ali"
readonly NAME
NAME="Qadiri"

3
JGI JAIN
DEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

The output of the given script is as follows:


/bin/sh: NAME: This variable is read only.

12.2.5 Unsetting Variables


When you unset or delete a variable, the shell removes it from the list of variables it keeps track of. You
cannot access the stored value of a variable once it has been unset.
Following is the syntax to unset a defined variable using the unset command:
unset variable_name
The command above unsets a specified variable’s value. Here is a basic example to show you how the
command works:
#!/bin/sh
NAME="Zara Ali"
unset NAME
echo $NAME
Nothing is printed in the preceding example. Variables defined as read only cannot be unset with the
unset command.

12.2.6 Types of Variables


Three sorts of variables are present when a shell is running, these variables are as follows:
 Local variable: A local variable is a variable that exists just in the current shell instance. Programs
that are started by the shell do not have access to it. At the command prompt, they are set.
 Environment variable: A variable that specify the behaviour of the environment. Any shell child
process has access to an environment variable. Some applications require environment variables to
work correctly. In most cases, a shell script merely defines environment variables that are required
by the applications it runs.
 Shell variable: A shell variable is a specific variable that the shell creates and that the shell needs
to function properly. Some of these factors are related to the environment, while others are related
to the local environment.

12.3 ENVIRONMENT VARIABLES


The behaviour of the environment is defined by environment variables or ENVs. They have the potential
to alter ongoing processes or initiatives in the environment.
Any shell child process has access to an environment variable. Some applications require environment
variables to work correctly. In most cases, a shell script merely defines environment variables that are
required by the applications it runs.

12.3.1 Scope of an Environment Variable


The scope of any variable refers to the area in which it may be accessed or defined. In Linux, an
environment variable can have a global or local scope.

Global
A globally scoped ENV that is defined in a terminal can be accessed from any location inside that
terminal’s environment. That implies it may be used in any scripts, programmes, or processes that
execute in the terminal’s environment.

4
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

Local
Any application or process executing in the terminal cannot access a locally scoped ENV established in
the terminal. It can only be accessed from the terminal where it was defined.
The syntax to access the ENVs is:
How to access ENVs?
$NAME
Note that the same method is used to access both local and global environment variables.
The syntax to display the ENVs are as follows:
$ echo $NAME
The syntax to display all the Linux ENVs
$ printenv //displays all the global ENVs
or
$ set //display all the ENVs (global as well as local)
or
$ env //display all the global ENVs

12.4 SHELL SCRIPTS


A shell script is a computer programme that runs through the Unix/Linux shell and can be one of the
following:
 The Bourne Shell  The Korn Shell
 The C Shell  The GNU Bourne-Again Shell
A shell is a command-line interpreter, and shell scripts commonly execute file manipulation, programme
execution and text output.

12.4.1 Extended Shell Scripts


Shell scripts must include certain mandatory structures that instruct the shell environment what to do
and when. Most scripts, however, are more complicated than the one above.
After all, the shell is a full-fledged programming language with variables, control structures, and so on.
A script is still just a series of commands executed in order, no matter how complex it becomes.
The read command is used in the following script to receive input from the keyboard, assign it to the
variable PERSON, and eventually output it on STDOUT.
#!/bin/sh

# Author : Zara Ali


# Copyright (c) [Link]
# Script follows here:

echo "What is your name?"


read PERSON
echo "Hello, $PERSON"

5
JGI JAIN
DEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

The output of the given script is as follows:


$./[Link]
What is your name?
Zara Ali
Hello, Zara Ali
The subsequent part of this tutorial will cover Unix/Linux Shell Scripting in detail.

12.5 READ: MAkING SCRIPTS INTERACTIVE


Here are a few pointers for interactively utilising the UNIX or Linux shell. For most interactive usage,
I prefer the bash shell, it is accessible on almost every *nix flavour and is quite comfortable to use as a
login shell. /bin/sh, whether it points to bash or Bourne shell, should always be the root shell.

12.5.1 Bash
The up and down arrow keys will scroll through the history of previous commands in bash; the up and
down arrow keys will scroll through the history of previous commands in bash. Ctrl+r, on the other hand,
does a reverse search, matching any portion of the command line. When you press ESC, the selected
command will be put into the current shell, ready for you to edit. If you wish to run the command again
and know what characters it started with do it as follow:
bash$ ls /tmp
(list of files in /tmp)
bash$ touch /tmp/foo
bash$ !l
ls /tmp
(list of files in /tmp, now including /tmp/foo)
PageUp and PageDn, in addition to the arrow keys, can be used to travel to the beginning and end of the
command line.

12.5.2 ksh
You may improve the usability of ksh by adding history commands in either vi or emacs mode. Depending
on the specific conditions, there are a variety of options. exec ksh -o vi, set -o vi, or ksh -o vi (where “vi”
could be replaced by “emacs” if you prefer emacs mode).
If you wish to start a ksh session from another interactive shell, then simply type ksh in the command
prompt:
csh% # oh no, it's csh!
csh% ksh
ksh$ # phew, that's better
ksh$ # do some stuff under ksh
ksh$ # then leave it back at the csh prompt:
ksh$ exit
csh%
This will launch a new ksh session, from which you can quit and return to your prior shell. You could also
use the exec command to replace the csh (or whatever shell) with a ksh shell:
csh% # oh no, it's csh!
csh% exec ksh

6
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

ksh$ # do some stuff under ksh


ksh$ exit

login:
The only difference is that you do not receive your csh session back this time.
The history is the good stuff:
csh% ksh
ksh$ set -o vi
ksh$
# You can now edit the history with vi-like commands,
# and use ESC-k to access the history.
If you press ESC then k, you may scroll backwards through the command history by continuously
pressing k. To alter the commands, use vi command-mode and entry-mode commands, such as this:
ksh$ touch foo
ESC-k (enter vi mode, brings up the previous command)
w (skip to the next word, to go from "touch" to "foo"
cw (change word) bar (change "foo" to "bar")
ksh$ touch bar

12.6 USING COMMAND LINE ARGUMENTS


The arguments supplied at the command prompt with a command or script to be run are known as
command line arguments (also known as positional parameters). The parameters’ positions at the
command prompt, as well as the command’s or script’s location, are saved in matching variables. These
are unique shell variables. Figure 1 will assist you in comprehending them.

Command arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10.....

$0 $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10}

$# $*
Variable Description
%0 Represents the command or script.
$1 to $9 Represents arguments 1 through 9.
${10} and so on Represents arguments 10 and further.
$# Represents the total number of arguments.
$* Represent all arguments.
$$ Represents the PID of a running script.

Figure 1: Displays the Unique Shell Variable


Create a shell script called “command line [Link]” that will display the command line arguments
that were provided and tally the number of arguments, the value of the first argument and the Script’s
Process ID (PID).

7
JGI JAIN DEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

12.7 EXIT AND EXIT STATUS OF COMMAND


“$?” is a variable that stores the result of the last command executed. “echo $?” returns 0 if the previous
command was successfully run, and a non-zero value if an error occurred. “$?” is set to the exit status
of the most recently executed process by bash. By convention, a 0 signifies a successful exit, whereas a
non-zero signals a mistake. It may be used to see if the previous command was completed successfully.
It saves 0 if it has been completed correctly. “$?” can also be used in shell scripts to determine what to do
base on the results of the previous command by checking the exit status.

12.8 THE LOGICAL OPERATORS


Testing a Boolean expression results in a value, this is either True or False. In some cases, when you
need to test multiple Boolean expressions, you can use logical operators to combine multiple Boolean
expressions. The logical operators can be used to test multiple Boolean expressions which can be a
combination of expressions on files, string, and integers. The logical operators AND and OR with their
notations and usage are listed in Table 1:

Table 1: Listing the Notations for Logical Operators

Notation Stands for Used as Action


&& AND test Bool_Exp1 && test Bool_Exp2 Checks if both the Boolean expressions Bool_Exp1
and Bool_Exp2 are true
|| OR test Bool_Exp1 || test Bool_Exp2 Checks if any of the Boolean expressions, Bool_
Exp1 or Bool_Exp2 is true

The possible end results of testing multiple Boolean expressions with logical operators are listed in
Table 2:

Table 2: Listing the Possible End Results When Using Logical Operators

Result of First Logical Operator Result of Second Boolean End Boolean Result
Boolean Expression Expression
True && True True
True && False False
False && True False
False && False False
True || True True
True || False True
False || True True
False || False False

12.9 CONDITION BASED CONTROL STRUCTURE


Condition based control structure refers to the sequential flow of control in a program, where, the
execution of statements depends upon a condition. In a condition based control structure, once the
control has moved past a statement, whether by executing it of by skipping it depending upon result
of the of the test condition, it does not revert back to it. Once the control flows past a statement, that
statement cannot be executed.

8
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

The two varieties of condition based control structures are as follows:


 The if-fi control structure
 The case-esac control structure

12.9.1 The if-fi Control Structure


The if-fi control structure executes statements depending upon the result of the test condition. The
flexibility of usage of this control structure allows its usage in multiple ways. Let us begin with the most
basic pattern of this control structure.

The if-then-fi Control Structure


This control structure tests for a condition, the Boolean result of which determines if the following
statements will be executed or skipped. The syntax for using this control structure is as follows:
if test bool_expr
then
statement1
statement2
….
Fi
where,
 if is the keyword to start the control structure
 test is the keyword to test the Boolean expression
 bool_expr is the Boolean expression to be tested
 then is the keyword to execute the following statements if the condition evaluates to true
 statement1, statement2, etc. are the statements that need to be executed if the test condition
evaluates to true
 fi is the keyword that notifies the interpreter of the end of the if control structure
The usage and execution of the if-then-fi control structure in the shell script iftfi is shown in Figure 2:

Figure 2: Showing the Implementation of if-then-fi Control Structure in a Shell Script


In the example shown Figure 2, the test condition evaluates to true. Therefore, the control flows to then,
and therefore the statements following then are executed.

9
JGI JAIN
DEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

The if-then-else-fi Control Structure


This control structure allows execution of some statements mentioned in the else clause if the test
condition evaluates to false. The syntax for this control structure is as follows:
if test bool_expr
then
statement1
statement2

else
statement3
statement4

Fi
where,
 if is the keyword to start the control structure.
 test is the keyword to test the Boolean expression.
 bool_expr is the Boolean expression to be tested.
 then is the keyword to execute the following statements if the condition evaluates to true. If the test
condition evaluates to false, all the statements in the then clause will be skipped and the control
flows to the else clause.
 statement1, statement2, etc., are the statements that need to be executed if the test condition
evaluates to true.
 else is the keyword to execute the following statements if the condition evaluates to false.
 statement3, statement4, etc., are the statements that need to be executed if the test condition
evaluates to false.
 fi is the keyword that notifies the interpreter of the end of the if control structure.
The if-then-else-fi control structure in the shell script itef is shown in Figure 3:

Figure 3: Showing the Usage of the if-then-else-fi Control Structure if a Shell Script Itef

10
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

In the example shown Figure 3, the test condition evaluates to true. Therefore, the control flows to
then, and therefore, the statements following then are executed. Only one of the test conditions needs
to evaluate to true for the control to move to the then clause because of the OR logical operator used
between multiple test conditions. The test condition evaluates to true, therefore, the statements in the
else clause are not executed.

The if- elif-else-fi Control Structure

This control structure is the most advanced of the if-fi control structures. It evaluates the first test
condition and if the result is false, then the control moves to the next condition, and so on. If all the
conditions specified are false then the statements in the else clause are executed if it exists. If the result
of any of the test conditions evaluates to true, the rest of the conditions and the else clause are skipped.
The syntax of this control structure is as follows:
if test bool_expr1
then
statements1
elif test bool_expr2
then
statements2
elif test bool_expr3
then
statements3
else
statements_else
fi
where,
 if is the keyword to start the if control structure
 test is the keyword to test a Boolean expression
 bool_expr1 is the first Boolean expression
 statements1 are the statements that are executed if bool_expr1 evaluates to true
 elif is the keyword to specify another Boolean expression that needs to be tested if the previous
evaluates to false
 bool_expr2 is the second Boolean expression that is evaluated if bool_expr1 evaluates to false
 staements2 are executed if bool_expr2 evaluates to true
 else is the keyword to specify the statements to be executed if all the previous Boolean expressions
evaluate to false
 statements_else are executed if the control flows to else
 fi is the keyword to notify the interpreter of the end of the if control structure

11
JGI JAIN
DEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

The usage of this control structure in the shell script itetef is shown Figure 4:

Figure 4: Showing the Usage of Multiple test Conditions in One if-elif-else-fi Control Structure
In the example shown in Figure 4, multiple test conditions are included in the shell script itetef. In this
script, at most, one of the conditions can evaluate to true. Only the statements written in its then clause
will be executed after which the control flows to fi, i.e., the end of the if structure. Let us now study the
case-esac control structure, which is another type of conditional control structure to test multiple test
conditions.

12.9.2 The case-esac Control Structure


In a shell script, using the if-fi control structure for testing multiple test conditions makes a program
very long. Therefore, it is difficult to code and maintain such a program. In most cases, the case-esac
conditional control structure can be used to make such a program very short and still perform the same
functions.
The syntax for case-esac control structure is as follows:
case var in
value1) statement1;
statement2;;
value2) statement3;

12
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

statement4;;
………
………
valueN) statemenN;;
*) statement_else;;
esac
where,
 case is the keyword that notifies the interpreter of the start of a case control structure
 var is the variable that will be compared to multiple values
 value1, value2, valueN, etc. are the value that will be compared to the value held in var variable
 ) (right parantheses) are interpreted as the end of the test criteria and the beginning of the statements
that need to be executed if the value matches to the var variable
 * signifies the statements that will be executed if none of the values mentioned match with the value
held in var variable; this is similar to the else in if-then-fi control structure
 ; marks the end of every statement
 ;; marks the end of every group of statements in a test condition
 esac is interpreted as the end of the case control structure

The example of case-esac control structure and its usage to create the same program as illustrated in
Figure 4 in the shell script casedemo is shown in Figure 5:

Figure 5: The case-esac Control Structure

13
JGI JAINDEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

12.10 ITERATION BASED CONTROL STRUCTURE


Iteration based control structures are those that involve repetition of execution of statements depending
upon the result of a Boolean condition that is checked, repetitively.
There are three kinds of iteration based control structures in UNIX shell programming, which are
illustrated in Figure 6:

Iteration based control structures


while loop

until loop

for loop

Figure 6: Illustrating the Iteration Based Control Structures

12.10.1 The while Loop


The while loop is an iteration based control structure that executes the statements if the result of the
Boolean test expression evaluates to true. The syntax for the while loop is as follows:
while test bool_expr
do
statement1
statement2
……..
statementN
done
where,
 while is the keyword interpreted as the beginning of the control structure
 test is the keyword to test the Boolean expression
 do is the keyword that marks the beginning of the statements to be executed
 statement1, statement2, …., statementN are the statements that need to be executed is the result of
the Boolean expression evaluates to true
 done is the keyword that marks the end of statements

The flow of control starts from the while keyword to the test condition. If the condition evaluates to
true, the statements enclosed in the do and done keywords are executed. The control flows from done
keyword back to the test condition which is again checked. Depending upon the result of the Boolean
expression, the execution of the statements in do-done are executed. The cycle continues for as long as
the Boolean expression evaluates to true.

14
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

The usage of the while loop in the shell script whiledemo is shown in Figure 7:

Figure 7: Showing the Usage of while Loop in the Shell Script whiledemo

12.10.2 The Until Loop


The until loop is similar to the while loop in every manner except that the statements enclosed in the
do-done keywords are executed if the test condition evaluates to false. In while loop, the statements are
executed if the test condition evaluates to true. The syntax for using the until loop is as follows:
until test bool_expr
do
statement1
statement2
……..
statementN
done
where,
 until is the keyword interpreted as the beginning of the control structure
 test is the keyword to test the Boolean expression
 do is the keyword that marks the beginning of the statements to be executed
 statement1, statement2, …., statementN are the statements that need to be executed if the result of
the Boolean expression evaluates to false
 done is the keyword that marks the end of statements
Similar to the control flow of a while loop, the flow of control in until loop starts from the until keyword
and moves to the test condition. If the condition evaluates to false, then the statements enclosed in the do
and done keywords are executed. The control flows from done keyword back to the test condition which
is again checked. Depending upon the result of the Boolean expression, the execution of the statements
in do-done are executed. The cycle continues for as long as the Boolean expression evaluates to false and
terminates when the test condition evaluates to true.
The usage of until loop to write a shell script is illustrated in Figure 8:
15
JGI JAINDEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

Figure 8: Showing the Usage of the until Loop in the Shell Script untildemo

12.10.3 The for Loop


The examples of loops that you have seen till now are such that there are three values that determine
the number of times the loop will continue. These values are:
 The instantiation value: The instantiation value refers to the value that a variable is assigned while
it is declared. This is the value that is changed to in every loop so that the loop does not continue
infinitely.
 The value of increment: The increment refers to the change in the value of the instantiated variable
to bring it closer to the termination value.
 The termination value: The termination value refers to the value that, depending on the expression,
when met or crossed by the instantiation variable, the loop is terminated.

In the while and until loop, it takes a separate line in the shell script to mention each of these values. In
the for loop, all these values can be declared in one line, which makes the code more manageable.
The syntax for the for loop is as follows:
for var in {initial_value..termination_value..increment}
do
statement1
statement2
……….
statementN
done
where,
 for is the keyword to start the for loop
 var is the variable that will be incremented or decremented to meet the termination value

16
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

 { } (curly brackets) contain the values for instantiation, termination, and increment or decrement
 initial_value is the starting value of the var variable
 termination_value is the value that when reached by the var variable, the loop is terminated
 increment is the value with which the var variable is incremented or decremented
 .. (double dots) separate the initial value, termination value, and the increment
 do-done enclose the statements that will be executed for as long as the var does not equal the
termination_value
The usage of the for loop in the shell script fordemo to print a string entered by the user five times is
shown in Figure 9:

Figure 9: Showing the Usage of for Loop in the Shell Script fordemo
In the above example, the variable a is not declared explicitly but the value it is assigned is 1. The
termination value and the test condition was not required separately and was mentioned in the for loop
itself as 10. The increment was also not required to be done by the programmer separately. In the for
loop itself, the increment was mentioned as 2. This value is added to the variable a every time the loop
is executed.

12.10.4 Nesting Loops


Nesting is supported by all loops, which means you may put one loop within another similar or different
loop. Depending on your needs, this nesting can go up to an infinite number of times.

17
JGI JAIN
DEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

Here’s an example of a while loop that is nested. In a similar approach, the additional loops might be
layered dependent on the programming need. The syntax of nested loop is as follows:
while command1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if command1 is true
while command2 ; # this is loop2, the inner loop
do
Statement(s) to be executed if command2 is true
done
Statement(s) to be executed if command1 is true
done
The following script shows the concept of nested loop:
#!/bin/sh

a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b='expr $b - 1'
done
echo
a='expr $a + 1'
done
As a consequence, you will get the following outcome. It is crucial to understand how echo -n works in
this context. The -n option prevents echo from printing a newline character in this case. The output of
the given script is as follows:
0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0

12.11 HANDLING USING THE EXPR COMMAND


In Unix, the expr command evaluates a provided expression and shows the result. Basic integer
operations, such as addition, subtraction, multiplication, division and modulus are performed using
it. Regular expression evaluation, string operations, such as substring, length of strings and so on. The
syntax of the expr command is as follows:
$expr expression

18
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

The option of the expr command are as follows:


 - -version: It is used to show the version information.
Figure 10 shows the - -version of expr command:

Figure 10: The - -version of expr Command


 --help: It is used to show the help message and exit.
Figure 11 shows the - -help of expr command:

Figure 11: The - -Help of expr Command

19
JGI JAIN
DEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

12.12 LOOPING WITH A LIST USING THE LOOP


The for loop is used to go over a list of things. For each item in a list, it repeats a sequence of instructions.
Word1 to word N are sequences of characters separated by spaces, and var is the name of a variable
(words). The value of the variable var is set to the next word in the list of words, word1 to wordN, each
time the for loop runs.
The syntax of the for loop for looping the list is:
for var in word1 word2 ...wordn
do
Statement to be executed
Done
The following script shows the implementation of 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
The output of the given script is as follows:
$bash -f [Link]
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
The following script shows the implementation of 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
The output of the given script is as follows:
$bash -f [Link]
Iteration no 1
Iteration no 2
Iteration no 3

20
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

Iteration no 4
Iteration no 6
Iteration no 7
Iteration no 8
Iteration no 9
Iteration no 10

12.13 MANIPULATING THE POSITIONAL PARAMETERS USING SET AND SHIFT COMMAND
Positional parameters are automatically created like the variable REPLY, and their values cannot be
modified. These variables are therefore called automatic variables or read-only variables. Passing
arguments to a shell script when executing them are automatically stored in positional parameters.
The values delimited by a null character are considered separate values and are stored in different
variables.
The first value is stored in the variable 1, the second in variable 2, third in 3, and so on. The name of the
file acts as an argument to sh command and its name is stored in the variable 0. Similarly, the variable
* stores all the values entered by the user. The variable # stores the number of positional parameters
created to save the values entered by the user. As explained in previous chapters, the values held
inthese variables can be accessed using a $ followed by the variable name.
The usage of positional parameters and variables * and # in the shell script posparam and its execution
is shown in Figure 12:

Figure 12: Showing the Usage of Positional Parameters


The shift command shifts the values stored in the positional parameters deleting the first. For example,
if the value stored in positional parameters 1, 2, 3, and 4 are Hello, UNIX, Programming, and world
respectively, using the shift command will remove the first variable and store the values of the
subsequent variables in the preceding.
The values of 1, 2, 3, and 4 after using the shift command will be UNIX, Programming, world, and the
value in 4 will be null, respectively.

21
JGI JAIN
DEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

The implementation of the above example in the shell script posparam1 and its execution is shown in
Figure 13:

Figure 13: Showing the Usage of the Shift Command in the Script posparam1
The set command sets the value passed to it as an argument in the positional parameters. These
values held in the positional parameters can then be referred to using their variable names. The set
command can also be used to set the output of any command in the positional parameters by enclosing
the command in backticks and passing it as an argument to the set command. The usage of the set
command in a shell script is shown in Figure 14:

Figure 14: Showing the Usage of the Set Command and Positional Parameters

12.14 INTERRUPTING A PROGRAM USING THE TRAP COMMAND


Signals are software interruptions issued to a programme to mark the occurrence of a significant event.
User requests to unauthorised memory access errors are examples of occurrences. Some signals, such
as the interrupt signal, indicate that the programme has been requested to do an action that is not part
of the normal control flow. Table 3 contains typical signals that you could come across and desire to use
in your programmes:

22
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

Table 3: Typical Signals

Signal Name Signal Number Description


SIGHUP 1 Hang up detected on controlling terminal or death of controlling process
SIGINT 2 Issued if the user sends an interrupt signal (Ctrl + C)
SIGQUIT 3 Issued if the user sends a quit signal (Ctrl + D)
SIGFPE 8 Issued if an illegal mathematical operation is attempted
SIGKILL 9 If a process gets this signal it must quit immediately and will not perform
any clean-up operations
SIGALRM 14 The alarm clock signal (used for timers)
SIGTERM 15 Software termination signal (sent by kill by default)

If you just omit the first parameter after changing the default action to be done on receipt of a signal,
then you may modify it back with the trap.
$ trap 1 2
This returns the default action to be executed when signals 1 or 2 are received.

12.15 DEBUGGING SHELL SCRIPTS WITH THE SET –X COMMAND


When things do not go as planned, you will need to figure out why the script is not working. Bash has a
lot of debugging features. The most popular method is to launch the subshell with the -x option, which
forces the script to execute in debug mode. After the commands have been expanded but before they are
performed, traces of each command and its arguments are displayed to standard output.
This is the debug version of the [Link] script. Note that the additional remarks are not
apparent in the script’s output. Using the set Bash built-in, you may execute sections of the script in
normal mode that you are confident are error-free, while only displaying debugging information for
difficult zones. If we do not know what the w command in the sample [Link] will do, we
can encapsulate it in the script as follows:
set -x # activate debugging from here
w
set +x # stop debugging from here
Once you have identified the problematic section of your script, you may use echo statements before
each command that you are not sure about to see precisely where and why things are not working.

12.16 LAB EXERCISE


a. Write a shell script to display greeting message to the user.
Ans. The shell script to display a greeting message to the user is as follows:
hour=$(date +"%H")
# If it's between 12:00 a.m. and 12:00 p.m., say Good Morning.
if [ $hour -ge 0 -a $hour -lt 12 ]
then
greet="Good Morning, $USERNAME"
# If it's between 12:00 p.m. and 6:00 p.m., say Good Afternoon.
elif [ $hour -ge 12 -a $hour -lt 18 ]
then

23
JGI JAINDEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming

greet="Good Afternoon, $USERNAME"


# It is Good Evening till midnight.
else
greet="Good evening, $USER"
fi
echo $greet

Conclusion 12.17 CONCLUSION

 A shell program, often known as a shell script, is a program made up entirely of shell commands.
Every time a shell program is executed, it is interpreted
 Shell programmes can be written in any format as long as each shell command’s syntax is valid.
This allows for the usage of blank lines, indentation and a lot of whitespaces.
 An interface to the Unix system is provided via a Shell. It takes your input and uses it to run
applications. It shows the result of a programme once it has completed its execution.
 A variable is a character string that has a value attached to it. A number, text, filename, device, or
any other sort of data might be assigned as the value.
 The read-only command in Shell can be used to mark variables as read only.
 When you unset or delete a variable, shell removes it from the list of variables it keeps track of.
 A local variable is a variable that exists just in the current shell instance.
 Variables in the environment any shell child process has access to an environment variable. Some
applications require environment variables to work correctly.
 A shell variable is a specific variable that the shell creates and that the shell needs to function
properly.
 A globally scoped ENV that is defined in a terminal can be accessed from any location inside that
terminal’s environment.
 A shell script is a computer programme that runs through the Unix/Linux.
 A shell is a command-line interpreter, and shell scripts commonly execute file manipulation,
programme execution and text output.
 The arguments supplied at the command prompt with a command or script to be run are known as
command line arguments (also known as positional parameters).
 Testing a Boolean expression results in a value, this is either True or False. In some cases, when
you need to test multiple Boolean expressions, you can use logical operators to combine multiple
Boolean expressions.
 Condition based control structure refers to the sequential flow of control in a program, where, the
execution of statements depends upon a condition.
 The if-fi control structure executes statements depending upon the result of the test condition.
 In most cases, the case-esac conditional control structure can be used to make such a program very
short and still perform the same functions.
 Iteration based control structures are those that involve repetition of execution of statements
depending upon the result of a Boolean condition that is checked repetitively.

24
UNIT 12: Essential Shell Programming JGI JAIN
DEEMED-TO-BE UN IV E RSI TY

 Nesting is supported by all loops, which means you may put one loop within another similar or
different loop.
 In Unix, the expr command evaluates a provided expression and shows the result.
 Positional parameters are automatically created like the variable REPLY, and their values cannot
be modified.
 The shift command shifts the values stored in the positional parameters deleting the first.
 The set command sets the value passed to it as an argument in the positional parameters. These
values held in the positional parameters can then be referred to using their variable names.

12.18 GLOSSARY

 Shell script: It is a program made up entirely of shell commands. Every time a shell program is
executed, it is interpreted.
 Variable: It is a character string that has a value attached to it. A number, text, filename, device, or
any other sort of data might be assigned as the value.
 Shell variable: A specific variable that the shell creates and that the shell needs to function properly.
 Read-only variables: The read-only command in Shell can be used to mark variables as read-only.
A variable’s value cannot be modified after it has been designated as read-only.
 Resetting traps: If you just omit the first parameter after changing the default action to be done on
receipt of a signal, you may modify it back with the trap.
 List of signal: There is a simple technique to compile a list of all the signals that your system supports.
Simply use the kill -l command to get a list of all available signals.
 Until statement: The till loop is run until the condition/command evaluates to false again. When the
condition/command becomes true, the loop ends.

12.19 SELF ASSESSMENT QUESTIONS

A. Essay Type Questions


1. A variable is a character string that has a value attached to it. Discuss.
2. The behaviour of the environment is defined by environment variables. Explain the scope of ENVs.
3. What do you understand by command line argument?
4. Condition based control structure refers to the sequential flow of control in a program, where, the
execution of statements depends upon a condition. Discuss.
5. Explain the concept of iteration based control structure.

12.20 ANSWERS AND HINTS FOR SELF ASSESSMENT QUESTIONS

A. Hints for Essay Type Questions


1. A number, text, filename, device, or any other sort of data might be assigned as the value. A variable
is simply a reference to the real data. Variables can be created, assigned and deleted via the shell.
25
JGI JAINDEEMED-TO-BE UN IV E RSI TY
Operating System and Unix Shell Programming
Refer to Section Shell Variables
2. The scope of any variable refers to the area in which it may be accessed or defined. In Linux, an
environment variable can have a global or local scope. Refer to Section Environment Variables
3. The arguments supplied at the command prompt with a command or script to be run are known as
command line arguments (also known as positional parameters). The parameters’ positions at the
command prompt, as well as the command’s or script’s location, are saved in matching variables.
Refer to Section Using Command Line Arguments
4. In a condition based control structure, once the control has moved past a statement, whether by
executing it of by skipping it depending upon result of the of the test condition, it does not revert
back to it. Once the control flows past a statement, that statement cannot be executed. Refer to
Section Condition Based Control Structure
5. Iteration based control structures are those that involve repetition of execution of statements
depending upon the result of a Boolean condition that is checked repetitively. There are three kinds
of iteration based control structures in UNIX shell programming. Refer to Section Iteration Based
Control Structure

@ 12.21 POST-UNIT READING MATERIAL

 [Link]
 [Link]

12.22 TOPICS FOR DISCUSSION FORUMS

 Discuss with your friends the essential shell programming and their real-time scenario where they
are used.

26

You might also like