0% found this document useful (0 votes)
15 views46 pages

LINUX UNIT IV

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)
15 views46 pages

LINUX UNIT IV

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
You are on page 1/ 46

UNIT IV

SHELL PROGRAMMING

1. Linux - The vi Editor Tutorial


There are many ways to edit files in Unix. Editing files using the screen-oriented text
editor vi is one of the best ways. This editor enables you to edit lines in context with other
lines in the file.

An improved version of the vi editor which is called the VIM has also been made available
now. Here, VIM stands for Vi IMproved.

vi is generally considered the de facto standard in Unix editors because −

• It's usually available on all the flavors of Unix system.


• Its implementations are very similar across the board.
• It requires very few resources.
• It is more user-friendly than other editors such as the ed or the ex.

You can use the vi editor to edit an existing file or to create a new file from scratch. You can
also use this editor to just read a text file.

Starting the vi Editor


The following table lists out the basic commands to use the vi editor −

S. No. Command & Description

1
vi filename
Creates a new file if it already does not exist, otherwise opens an existing file.

2
vi -R filename
Opens an existing file in the read-only mode.

1|Page
3
view filename
Opens an existing file in the read-only mode.

Following is an example to create a new file testfile if it already does not exist in the current
working directory −
$vi testfile
The above command will generate the following output −
|
~
~
~
~
~
~
~
~
~
~
~
~
"testfile" [New File]
You will notice a tilde (~) on each line following the cursor. A tilde represents an unused
line. If a line does not begin with a tilde and appears to be blank, there is a space, tab, newline,
or some other non-viewable character present.

You now have one open file to start working on. Before proceeding further, let us understand
a few important concepts.

2. Operation Modes
While working with the vi editor, we usually come across the following two modes −

• Command mode − This mode enables you to perform administrative tasks


such as saving the files, executing the commands, moving the cursor, cutting
(yanking) and pasting the lines or words, as well as finding and replacing. In
this mode, whatever you type is interpreted as a command.
• Insert mode − This mode enables you to insert text into the file. Everything
that's typed in this mode is interpreted as input and placed in the file.

2|Page
vi always starts in the command mode. To enter text, you must be in the insert mode for
which simply type i. To come out of the insert mode, press the Esc key, which will take you
back to the command mode.

Hint − If you are not sure which mode you are in, press the Esc key twice; this will take you
to the command mode. You open a file using the vi editor. Start by typing some characters
and then come to the command mode to understand the difference.

3. Getting Out of vi
The command to quit out of vi is :q. Once in the command mode, type colon, and 'q', followed
by return. If your file has been modified in any way, the editor will warn you of this, and not
let you quit. To ignore this message, the command to quit out of vi without saving is :q!. This
lets you exit vi without saving any of the changes.

The command to save the contents of the editor is :w. You can combine the above command
with the quit command, or use :wq and return.

The easiest way to save your changes and exit vi is with the ZZ command. When you are in
the command mode, type ZZ. The ZZ command works the same way as the :wq command.

If you want to specify/state any particular name for the file, you can do so by specifying it
after the :w. For example, if you wanted to save the file you were working on as another
filename called filename2, you would type :w filename2 and return.

4. Moving within a File


To move around within a file without affecting your text, you must be in the command mode
(press Esc twice). The following table lists out a few commands you can use to move around
one character at a time −

S. No. Command & Description

1
k - oves the cursor up one line

3|Page
2
j - Moves the cursor down one line

3
h - Moves the cursor to the left one-character position

4
l - Moves the cursor to the right one-character position

The following points need to be considered to move within a file −

• vi is case-sensitive. You need to pay attention to capitalization when using the


commands.
• Most commands in vi can be prefaced by the number of times you want the
action to occur. For example, 2j moves the cursor two lines down the cursor
location.

There are many other ways to move within a file in vi. Remember that you must be in the
command mode (press Esc twice). The following table lists out a few commands to move
around the file −

Given below is the list of commands to move around the file.

5. Control Commands
The following commands can be used with the Control Key to performs functions as given in
the table below −

Given below is the list of control commands.

a) Editing Files

To edit the file, you need to be in the insert mode. There are many ways to enter the insert
mode from the command mode −

Sr.No. Command & Description

1
i - Inserts text before the current cursor location

4|Page
2
I - Inserts text at the beginning of the current line

3
a - Inserts text after the current cursor location

4
A - Inserts text at the end of the current line

5
o - Creates a new line for text entry below the cursor location

6
O - Creates a new line for text entry above the cursor location

b) Deleting Characters
Here is a list of important commands, which can be used to delete characters and lines in an
open file −

S. No. Command & Description

1
x - Deletes the character under the cursor location

2
X - Deletes the character before the cursor location

3
Dw - Deletes from the current cursor location to the next word

4
d^ - Deletes from the current cursor position to the beginning of the line

5
d$ - Deletes from the current cursor position to the end of the line

6
D - Deletes from the cursor position to the end of the current line

7
Dd - Deletes the line the cursor is on

5|Page
As mentioned above, most commands in vi can be prefaced by the number of times you want
the action to occur. For example, 2x deletes two characters under the cursor location
and 2dd deletes two lines the cursor is on.

6. Change Commands
You also have the capability to change characters, words, or lines in vi without deleting them.
Here are the relevant commands −

S.No. Command & Description

1
cc - Removes the contents of the line, leaving you in insert mode.

2
cw - Changes the word the cursor is on from the cursor to the lowercase w end of the
word.

3
r - Replaces the character under the cursor. vi returns to the command mode after the
replacement is entered.

4
R - Overwrites multiple characters beginning with the character currently under the
cursor. You must use Esc to stop the overwriting.

5
s - Replaces the current character with the character you type. Afterward, you are left in
the insert mode.

6
S - Deletes the line the cursor is on and replaces it with the new text. After the new text
is entered, vi remains in the insert mode.

7. Copy and Paste Commands


You can copy lines or words from one place and then you can paste them at another place
using the following commands −.

6|Page
S.No. Command & Description

1
yy - Copies the current line.

2
yw - Copies the current word from the character the lowercase w cursor is on, until the end
of the word.

3
p - Puts the copied text after the cursor.

4
P - Puts the yanked text before the cursor.

7|Page
I Variables

A variable is a character string to which we assign a value. The value assigned could be a
number, text, filename, device, or any other type of data.

A variable is nothing more than a pointer to the actual data. The shell enables you to create,
assign, and delete variables.

a) Variable Names

The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or the
underscore character ( _).

By convention, Unix shell variables will have their names in UPPERCASE.

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!
The reason you cannot use other characters such as !, *, or - is that these characters have a
special meaning for the shell.

b) Defining Variables

Variables are defined as follows −

variable_name=variable_value
For example −
NAME="Zara Ali"
The above example defines the variable NAME and assigns the value "Zara Ali" to it. Variables
of this type are called scalar variables. A scalar variable can hold only one value at a time.

8|Page
Shell enables you to store any value you want in a variable. For example −

VAR1="Zara Ali"
VAR2=100

c) Accessing Values
To access the value stored in a variable, prefix its name with the dollar sign ($) −
For example, the following script will access the value of defined variable NAME and print it
#!/bin/sh

NAME="Zara Ali"
echo $NAME
The above script will produce the following value −
Zara Ali

d) Read-only Variables
Shell provides a way to mark variables as read-only by using the read-only command. After
a variable is marked read-only, its value cannot be changed.

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"
The above script will generate the following result −
/bin/sh: NAME: This variable is read only.

II Unsetting Variables
Unsetting or deleting a variable directs the shell to remove the variable from the list of
variables that it tracks. Once you unset a variable, you cannot access the stored value in the
variable.

9|Page
Following is the syntax to unset a defined variable using the unset command −

unset variable_name
The above command unsets the value of a defined variable. Here is a simple example that
demonstrates how the command works −

#!/bin/sh

NAME="Zara Ali"
unset NAME
echo $NAME
The above example does not print anything. You cannot use the unset command
to unset variables that are marked readonly.

III Variable Types


When a shell is running, three main types of variables are present −

➢ Local Variables − A local variable is a variable that is present within the


current instance of the shell. It is not available to programs that are started by
the shell. They are set at the command prompt.
➢ Environment Variables − An environment variable is available to any child
process of the shell. Some programs need environment variables in order to
function correctly. Usually, a shell script defines only those environment
variables that are needed by the programs that it runs.
➢ Shell Variables − A shell variable is a special variable that is set by the shell
and is required by the shell in order to function correctly. Some of these
variables are environment variables whereas others are local variables.

The following table shows a number of special variables that you can use in your shell scripts

S.No. Variable & Description

1
$0 - The filename of the current script.

10 | P a g e
2
$n - These variables correspond to the arguments with which a script was invoked.
Here n is a positive decimal number corresponding to the position of an argument (the first
argument is $1, the second argument is $2, and so on).

3
$# - The number of arguments supplied to a script.

4
$* - All the arguments are double quoted. If a script receives two arguments, $* is equivalent
to $1 $2.

5
$@ - All the arguments are individually double quoted. If a script receives two arguments,
$@ is equivalent to $1 $2.

6
$? - The exit status of the last command executed.

7
$$ - The process number of the current shell. For shell scripts, this is the process ID under
which they are executing.

8
$! - The process number of the last background command.

IV Command-Line Arguments
➢ The command-line arguments $1, $2, $3, ...$9 are positional parameters, with $0
pointing to the actual command, program, shell script, or function and $1, $2, $3, ...$9
as the arguments to the command.

➢ Following script uses various special variables related to the command line −

#!/bin/sh

echo "File Name: $0"


echo "First Parameter : $1"
echo "Second Parameter : $2"
echo "Quoted Values: $@"
echo "Quoted Values: $*"
echo "Total Number of Parameters : $#"
➢ Here is a sample run for the above script −

11 | P a g e
$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2

V Special Parameters $* and $@


➢ There are special parameters that allow accessing all the command-line arguments at
once. $* and $@ both will act the same unless they are enclosed in double quotes, "".

➢ Both the parameters specify the command-line arguments. However, the "$*" special
parameter takes the entire list as one argument with spaces between and the "$@"
special parameter takes the entire list and separates it into separate arguments.

➢ We can write the shell script as shown below to process an unknown number of
command line arguments with either the $* or $@ special parameters –

#!/bin/sh
for TOKEN in $*
do
echo $TOKEN
done
Here is a sample run for the above script −
$./test.sh Zara Ali 10 Years Old
Zara
Ali
10
Years
Old
Note − Here do...done is a kind of loop that will be covered in a subsequent tutorial.

VI Exit Status
• The $? variable represents the exit status of the previous command.

12 | P a g e
• Exit status is a numerical value returned by every command upon its completion. As
a rule, most commands return an exit status of 0 if they were successful, and 1 if they
were unsuccessful.

• Some commands return additional exit statuses for particular reasons. For example,
some commands differentiate between kinds of errors and will return various exit
values depending on the specific type of failure.

Following is the example of successful command −


$./test.sh Zara Ali
File Name : ./test.sh
First Parameter : Zara
Second Parameter : Ali
Quoted Values: Zara Ali
Quoted Values: Zara Ali
Total Number of Parameters : 2
$echo $?
0
$

VII Linux - Shell Arrays


A shell variable is capable enough to hold a single value. These variables are called scalar
variables.

Shell supports a different type of variable called an array variable. This can hold multiple
values at the same time. Arrays provide a method of grouping a set of variables. Instead of
creating a new name for each variable that is required, you can use a single array variable
that stores all the other variables.

All the naming rules discussed for Shell Variables would be applicable while naming arrays.

i. Defining Array Values

The difference between an array variable and a scalar variable can be explained as follows.

Suppose you are trying to represent the names of various students as a set of variables. Each
of the individual variables is a scalar variable as follows –

13 | P a g e
NAME01="Zara"
NAME02="Qadir"
NAME03="Mahnaz"
NAME04="Ayan"
NAME05="Daisy"
We can use a single array to store all the above-mentioned names. Following is the simplest
method of creating an array variable. This helps assign a value to one of its indices.

array_name[index]=value

Here array_name is the name of the array, index is the index of the item in the array that you
want to set, and value is the value you want to set for that item.

As an example, the following commands −

NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
If you are using the ksh shell, here is the syntax of array initialization −

set -A array_name value1 value2 ... valuen

If you are using the bash shell, here is the syntax of array initialization −

array_name=(value1 ... valuen)

ii. Accessing Array Values


After you have set any array variable, you access it as follows −

${array_name[index]}

Here array_name is the name of the array, and index is the index of the value to be accessed.
Following is an example to understand the concept −

#!/bin/sh

NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"

14 | P a g e
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
The above example will generate the following result −

$./test.sh
First Index: Zara
Second Index: Qadir

You can access all the items in an array in one of the following ways −

${array_name[*]}
${array_name[@]}

Here array_name is the name of the array you are interested in. Following example will help
you understand the concept −

#!/bin/sh

NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Method: ${NAME[*]}"
echo "Second Method: ${NAME[@]}"
The above example will generate the following result −

$./test.sh
First Method: Zara Qadir Mahnaz Ayan Daisy
Second Method: Zara Qadir Mahnaz Ayan Daisy

VIII Shell Basic Operators


There are various operators supported by each shell. We will discuss in detail about Bourne
shell (default shell)
We will now discuss the following operators −

• Arithmetic Operators
• Relational Operators

15 | P a g e
• Boolean Operators
• String Operators
• File Test Operators
Bourne shell didn't originally have any mechanism to perform simple arithmetic operations
but it uses external programs, either awk or expr.

The following example shows how to add two numbers −

#!/bin/sh
val=`expr 2 + 2`
echo "Total value : $val"

The above script will generate the following result −

Total value: 4

The following points need to be considered while adding −

• There must be spaces between operators and expressions. For example, 2+2 is
not correct; it should be written as 2 + 2.
• The complete expression should be enclosed between ‘ ‘, called the backtick.

a) Arithmetic Operators

The following arithmetic operators are supported by Bourne Shell.


Assume variable a holds 10 and variable b holds 20 then −

Operator Description Example

+ (Addition) Adds values on either side of the operator `expr $a + $b` will give 30

- (Subtraction) Subtracts right hand operand from left hand operand `expr $a - $b` will give -10

* (Multiplication) Multiplies values on either side of the operator `expr $a \* $b` will give
200

16 | P a g e
/ (Division) Divides left hand operand by right hand operand `expr $b / $a` will give 2

% (Modulus) Divides left hand operand by right hand operand and `expr $b % $a` will give 0
returns remainder

= (Assignment) a = $b would assign value


Assigns right operand in left operand of b into a

== (Equality) Compares two numbers, if both are same then [ $a == $b ] would return
returns true. false.

!= (Not Equality) Compares two numbers, if both are different then [ $a != $b ] would return
returns true. true.

It is very important to understand that all the conditional expressions should be inside
square braces with spaces around them, for example [ $a == $b ] is correct
whereas, [$a==$b] is incorrect.

All the arithmetical calculations are done using long integers.

b) Relational Operators
Bourne Shell supports the following relational operators that are specific to numeric values.
These operators do not work for string values unless their value is numeric.

For example, following operators will work to check a relation between 10 and 20 as well as
in between "10" and "20" but not in between "ten" and "twenty".

Assume variable a holds 10 and variable b holds 20 then −

Operator Description Example

-eq Checks if the value of two operands are equal or not; if yes, then [ $a -eq $b ] is not true.
the condition becomes true.

17 | P a g e
-ne Checks if the value of two operands are equal or not; if values are
[ $a -ne $b ] is true.
not equal, then the condition becomes true.

-gt Checks if the value of left operand is greater than the value of
[ $a -gt $b ] is not true.
right operand; if yes, then the condition becomes true.

-lt Checks if the value of left operand is less than the value of right
[ $a -lt $b ] is true.
operand; if yes, then the condition becomes true.

-ge Checks if the value of left operand is greater than or equal to the
[ $a -ge $b ] is not true.
value of right operand; if yes, then the condition becomes true.

-le Checks if the value of left operand is less than or equal to the
[ $a -le $b ] is true.
value of right operand; if yes, then the condition becomes true.

It is very important to understand that all the conditional expressions should be placed
inside square braces with spaces around them. For example, [ $a <= $b ] is correct
whereas, [$a <= $b] is incorrect.

c) Boolean Operators

The following Boolean operators are supported by the Bourne Shell.

Assume variable a holds 10 and variable b holds 20 then −

Operator Description Example

! This is logical negation. This inverts a true condition


[ ! false ] is true.
into false and vice versa.

-o This is logical OR. If one of the operands is true, then [ $a -lt 20 -o $b -gt 100 ] is true.
the condition becomes true.

-a This is logical AND. If both the operands are true, then


[ $a -lt 20 -a $b -gt 100 ] is false.
the condition becomes true otherwise false.

d) String Operators
The following string operators are supported by Bourne Shell.

18 | P a g e
Assume variable a holds "abc" and variable b holds "efg" then −

Operator Description Example

= Checks if the value of two operands are equal or not; if [ $a = $b ] is not true.
yes, then the condition becomes true.

!= Checks if the value of two operands are equal or not; if [ $a != $b ] is true.


values are not equal then the condition becomes true.

-z Checks if the given string operand size is zero; if it is [ -z $a ] is not true.


zero length, then it returns true.

-n Checks if the given string operand size is non-zero; if it is [ -n $a ] is not false.


nonzero length, then it returns true.

str Checks if str is not the empty string; if it is empty, then it [ $a ] is not false.
returns false.

19 | P a g e
I. Linux - Shell Decision Making
While writing a shell script, there may be a situation when you need to adopt one path out of
the given two paths. So, you need to make use of conditional statements that allow your
program to make correct decisions and perform the right actions.

Unix Shell supports conditional statements which are used to perform different actions
based on different conditions. We will now understand two decision-making statements
here −

• The if...else statement


• The case...esac statement

a) The if...else statements


If else statements are useful decision-making statements which can be used to select an
option from a given set of options.

Unix Shell supports following forms of if…else statement −

• if...fi statement

• if...else...fi statement
• if...elif...else...fi statement

(i) The if...fi statement


The if...fi statement is the fundamental control statement that allows Shell to make decisions
and execute statements conditionally.

Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
fi

The Shell expression is evaluated in the above syntax. If the resulting value is true,
given statement(s) are executed. If the expression is false then no statement would be
executed. Most of the times, comparison operators are used for making decisions.

20 | P a g e
It is recommended to be careful with the spaces between braces and expression. No space
produces a syntax error.

If expression is a shell command, then it will be assumed true if it returns 0 after execution.
If it is a Boolean expression, then it would be true if it returns true.

Example
#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
echo "a is equal to b"
fi

if [ $a != $b ]
then
echo "a is not equal to b"
fi
The above script will generate the following result −
a is not equal to b

(ii) The if...else...fi statement


The if...else...fi statement is the next form of control statement that allows Shell to execute
statements in a controlled way and make the right choice.

Syntax
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
fi

The Shell expression is evaluated in the above syntax. If the resulting value is true,
given statement(s) are executed. If the expression is false, then no statement will be executed.

21 | P a g e
Example

The above example can also be written using the if...else statement as follows −

#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
Upon execution, you will receive the following result −
a is not equal to b

(iii) The if...elif...fi statement


The if...elif...fi statement is the one level advance form of control statement that allows Shell
to make correct decision out of several conditions.

Syntax
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi

This code is just a series of if statements, where each if is part of the else clause of the
previous statement. Here statement(s) are executed based on the true condition, if none of
the condition is true then else block is executed.

22 | P a g e
Example
#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "None of the condition met"
fi
Upon execution, you will receive the following result −
a is less than b

(iv) The case...esac Statement


You can use multiple if...elif statements to perform a multiway branch. However, this is not
always the best solution, especially when all of the branches depend on the value of a single
variable.

Unix Shell supports case...esac statement which handles exactly this situation, and it does
so more efficiently than repeated if...elif statements.

You can use multiple if...elif statements to perform a multiway branch. However, this is not
always the best solution, especially when all of the branches depend on the value of a single
variable.

Shell supports case...esac statement which handles exactly this situation, and it does so
more efficiently than repeated if...elif statements.

23 | P a g e
Syntax

The basic syntax of the case...esac statement is to give an expression to evaluate and to
execute several different statements based on the value of the expression.

The interpreter checks each case against the value of the expression until a match is found.
If nothing matches, a default condition will be used.

case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac
Here the string word is compared against every pattern until a match is found. The
statement(s) following the matching pattern executes. If no matches are found, the case
statement exits without performing any action.

There is no maximum number of patterns, but the minimum is one.

When statement(s) part executes, the command ;; indicates that the program flow should
jump to the end of the entire case statement. This is similar to break in the C programming
language.

Example
#!/bin/sh

FRUIT="kiwi"

case "$FRUIT" in
"apple") echo "Apple pie is quite tasty."
;;
"banana") echo "I like banana nut bread."

24 | P a g e
;;
"kiwi") echo "New Zealand is famous for kiwi."
;;
esac
Upon execution, you will receive the following result −

New Zealand is famous for kiwi.

A good use for a case statement is the evaluation of command line arguments as follows −

#!/bin/sh

option="${1}"
case ${option} in
-f) FILE="${2}"
echo "File name is $FILE"
;;
-d) DIR="${2}"
echo "Dir name is $DIR"
;;
*)
echo "`basename ${0}`:usage: [-f file] | [-d directory]"
exit 1 # Command to come out of the program with status 1
;;
esac
Here is a sample run of the above program −
$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d unix
Dir name is unix
$

25 | P a g e
II. Shell Loop Types
a) The while Loop
The while loop enables you to execute a set of commands repeatedly until some condition
occurs. It is usually used when you need to manipulate the value of a variable repeatedly.

Syntax
while command
do
Statement(s) to be executed if command is true
done
Here the Shell command is evaluated. If the resulting value is true, given statement(s) are
executed. If command is false then no statement will be executed and the program will jump
to the next line after the done statement.

Example
Here is a simple example that uses the while loop to display the numbers zero to nine −
#!/bin/sh

a=0

while [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9
Each time this loop executes, the variable a is checked to see whether it has a value that is
less than 10. If the value of a is less than 10, this test condition has an exit status of 0. In this
case, the current value of a is displayed and later a is incremented by 1.
26 | P a g e
Nesting Loops
All the loops support nesting concept which means you can put one loop inside another
similar one or different loops. This nesting can go up to unlimited number of times based on
your requirement.

Here is an example of nesting while loop. The other loops can be nested based on the
programming requirement in a similar way −

Nesting while Loops


It is possible to use a while loop as part of the body of another while loop.

Syntax
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

Example
Here is a simple example of loop nesting. Let's add another countdown loop inside the loop
that you used to count to nine −

#!/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`

27 | P a g e
done
This will produce the following result. It is important to note how echo -n works here. Here -
n option lets echo avoid printing a new line character.
0
10
210
3210
43210
543210
6543210
76543210
876543210
9876543210

b) The for Loop


The for loop operates on lists of items. It repeats a set of commands for every item in a list.

Syntax
for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done

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.

Example

Here is a simple example that uses the for loop to span through the given list of numbers −

#!/bin/sh

for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
Upon execution, you will receive the following result −
0
1

28 | P a g e
2
3
4
5
6
7
8
9
Following is the example to display all the files starting with .bash and available in your
home. We will execute this script from my root −

#!/bin/sh

for FILE in $HOME/.bash*


do
echo $FILE
done
The above script will produce the following result −
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc

c) The until Loop


The while loop is perfect for a situation where you need to execute a set of commands while
some condition is true. Sometimes you need to execute a set of commands until a condition
is true.

Syntax
until command
do
Statement(s) to be executed until command is true
done

Here the Shell command is evaluated. If the resulting value is false, given statement(s) are
executed. If the command is true then no statement will be executed and the program jumps
to the next line after the done statement.

29 | P a g e
Example

Here is a simple example that uses the until loop to display the numbers zero to nine −

#!/bin/sh

a=0

until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5
6
7
8
9

d) The select Loop

The select loop provides an easy way to create a numbered menu from which users can
select options. It is useful when you need to ask the user to choose one or more items from a
list of choices.

Syntax
select var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done

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.

30 | P a g e
For every selection, a set of commands will be executed within the loop. This loop was
introduced in ksh and has been adapted into bash. It is not available in sh.

Example
Here is a simple example to let the user select a drink of choice −
#!/bin/ksh

select DRINK in tea cofee water juice appe all none


do
case $DRINK in
tea|cofee|water|all)
echo "Go to canteen"
;;
juice|appe)
echo "Available at home"
;;
none)
break
;;
*) echo "ERROR: Invalid selection"
;;
esac
done
The menu presented by the select loop looks like the following −
$./test.sh
1) tea
2) cofee
3) water
4) juice
5) appe
6) all
7) none
#? juice
Available at home
#? none
$
You can change the prompt displayed by the select loop by altering the variable PS3 as
follows −
$PS3 = "Please make a selection => " ; export PS3
$./test.sh
1) tea
2) cofee
3) water

31 | P a g e
4) juice
5) appe
6) all
7) none
Please make a selection => juice
Available at home
Please make a selection => none
$

IX Shell Loop Control


So far you have looked at creating loops and working with loops to accomplish different
tasks. Sometimes you need to stop a loop or skip iterations of the loop.

In this chapter, we will learn following two statements that are used to control shell loops−

• The break statement


• The continue statement

The infinite Loop


All the loops have a limited life and they come out once the condition is false or true
depending on the loop.
A loop may continue forever if the required condition is not met. A loop that executes forever
without terminating executes for an infinite number of times. For this reason, such loops are
called infinite loops.

Example
Here is a simple example that uses the while loop to display the numbers zero to nine −
#!/bin/sh

a=10

until [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done
This loop continues forever because a is always greater than or equal to 10 and it is never
less than 10.

32 | P a g e
X The break Statement
The break statement is used to terminate the execution of the entire loop, after completing
the execution of all of the lines of code up to the break statement. It then steps down to the
code following the end of the loop.

Syntax
The following break statement is used to come out of a loop −

break

The break command can also be used to exit from a nested loop using this format −

break n

Here n specifies the nth enclosing loop to the exit from.

Example
Here is a simple example which shows that loop terminates as soon as a becomes 5 −

#!/bin/sh

a=0

while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done
Upon execution, you will receive the following result −
0
1
2
3
4
5

33 | P a g e
Here is a simple example of nested for loop. This script breaks out of both loops if var1
equals 2 and var2 equals 0 −

#!/bin/sh

for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
fi
done
done
Upon execution, you will receive the following result. In the inner loop, you have a break
command with the argument 2. This indicates that if a condition is met you should break out
of outer loop and ultimately from the inner loop as well.

10
15

XI The continue statement


The continue statement is similar to the break command, except that it causes the current
iteration of the loop to exit, rather than the entire loop.

This statement is useful when an error has occurred but you want to try to execute the next
iteration of the loop.

Syntax
continue

Like with the break statement, an integer argument can be given to the continue command
to skip commands from nested loops.

continue n

Here n specifies the nth enclosing loop to continue from.

34 | P a g e
Example

The following loop makes use of the continue statement which returns from the continue
statement and starts processing the next statement −

#!/bin/sh

NUMS="1 2 3 4 5 6 7"

for NUM in $NUMS


do
Q=`expr $NUM % 2`
if [ $Q -eq 0 ]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done
Upon execution, you will receive the following result −
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number

35 | P a g e
I Shell Substitution
What is Substitution?
The shell performs substitution when it encounters an expression that contains one or more
special characters.

Example

Here, the printing value of the variable is substituted by its value. Same time, "\n" is
substituted by a new line −

#!/bin/sh

a=10
echo -e "Value of a is $a \n"
You will receive the following result. Here the -e option enables the interpretation of
backslash escapes.

Value of a is 10

Following is the result without -e option −

Value of a is 10\n

The following escape sequences which can be used in echo command −

S.No. Escape & Description

1
\\ backslash

2
\a alert (BEL)

3
\b backspace

4
\c suppress trailing newline

36 | P a g e
5
\f form feed

6
\n new line

7
\r carriage return

8
\t horizontal tab

9
\v vertical tab

You can use the -E option to disable the interpretation of the backslash escapes (default).

You can use the -n option to disable the insertion of a new line.

a) Command Substitution
Command substitution is the mechanism by which the shell performs a given set of
commands and then substitutes their output in the place of the commands.

Syntax

The command substitution is performed when a command is given as −

`command`

When performing the command substitution make sure that you use the backquote, not the
single quote character.

Example

Command substitution is generally used to assign the output of a command to a variable.


Each of the following examples demonstrates the command substitution −

#!/bin/sh

DATE=`date`
echo "Date is $DATE"

USERS=`who | wc -l`
echo "Logged in user are $USERS"

37 | P a g e
UP=`date ; uptime`
echo "Uptime is $UP"
Upon execution, you will receive the following result −
Date is Thu Jul 2 03:59:57 MST 2009
Logged in user are 1
Uptime is Thu Jul 2 03:59:57 MST 2009
03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15

b) Variable Substitution
Variable substitution enables the shell programmer to manipulate the value of a variable
based on its state.

Here is the following table for all the possible substitutions −

Sr.No. Form & Description

1
${var} - Substitute the value of var.

2
${var:-word} - If var is null or unset, word is substituted for var. The value of var does not
change.

3
${var:=word} - If var is null or unset, var is set to the value of word.

4
${var:?message} - If var is null or unset, message is printed to standard error. This checks
that variables are set correctly.

5
${var:+word} - If var is set, word is substituted for var. The value of var does not change.

Example
Following is the example to show various states of the above substitution −
#!/bin/sh

echo ${var:-"Variable is not set"}


echo "1 - Value of var is ${var}"

echo ${var:="Variable is not set"}

38 | P a g e
echo "2 - Value of var is ${var}"

unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var"

var="Prefix"
echo ${var:+"This is default value"}
echo "4 - Value of var is $var"

echo ${var:?"Print this message"}


echo "5 - Value of var is ${var}"
Upon execution, you will receive the following result −
Variable is not set
1 - Value of var is
Variable is not set
2 - Value of var is Variable is not set

3 - Value of var is
This is default value
4 - Value of var is Prefix
Prefix
5- Value of var is Prefix

II. Set Command


Linux set command is used to set and unset certain flags or settings within the shell
environment. These flags and settings determine the behavior of a defined script and help in
executing the tasks without facing any issue. The values of shell attributes and parameters
can be changed or displayed by using the set command.

Syntax:

set [options]

Options: The supported options by the set command are as following:

o -a: It is used to mark variables that are modified or created for export.
o -b: It is used to notify of job termination immediately.
o -e: It is used to exit immediately if a command exits with a non-zero status.

39 | P a g e
o -f: It is used to disable the file name generation (globbing).
o -h: It is used to save the location of commands where they looked up.
o -k: It is used to place all assignment arguments in the environment variable of a
command, except those that precede the command name.
o -m: It is used to enable Job control.
o -n: It is used to read commands.
o -o: It is used for option-name.
o -p: It is used to disable the processing of the '$ENV' file and import shell functions. It
is turned on whenever the real and effective user ids do not match. Turning off this
option may cause the working uid and gid to be set as the authorized uid and gid.
o -t: It is used to exit from the command after executing one command.
o -u: It is used to treat unset variables as an error when substituting.
o -v: It is used to print shell input lines.
o -x: It is used to print commands and their arguments in a sequential way (as they are
executed).
o -B: It is used to perform brace expansion by the Shell.
o -C: It is used to disallow existing regular files to be overwritten by redirection of
output.
o -E: It is used if the ERR trap is inherited by the shell functions.
o -H: It is used to enable style history substitution. By default, it is on when the shell is
interactive.
o -P: It is used if we do not want to follow symbolic links when executing commands.
o -T: If this flag is set, the DEBUG trap is inherited by the shell functions.

Examples of the set command

Turn debugging information on or off.

The '-x' option is used with the set command to show command and their arguments. It is
useful for debugging the shell script.

Execute the following command:

To turn on the debugging information:

40 | P a g e
set -x
To turn off the debugging information:

set +x
Disable Bash's default behavior.

To disable the default behavior of Bash, execute the command as follows:

set -C
Stop a script immediately.

To stop a script immediately, execute the following command:

set -e
III. Shift Positional Parameters
Shift is a builtin command in bash which after getting executed, shifts/move the
command line arguments to one position left. The first argument is lost after using
shift command. This command takes only one integer as an argument. This
command is useful when you want to get rid of the command line arguments which
are not needed after parsing them.

Syntax:
shift n

Here, n is the number of positions by which you want to shift command-line


arguments to the left if you do not specify, the default value of n is assumed to be 1
i.e shift works the same as shift 1.

Example: Let’s create a shell script file named as sampleshift.sh as follows. The total
number of command-line arguments is represented by $#. Use the following
command to create the desired shell script file
vi sampleshift.sh

41 | P a g e
Now paste the following code:
#!/bin/bash

# total number of command-line arguments


echo "Total arguments passed are: $#"

# $* is used to show the command line arguments


echo "The arguments are: $*"

echo "The First Argument is: $1"


shift 2

echo "The First Argument After Shift 2 is: $1"


shift

echo "The First Argument After Shift is: $1"


Now to save the file press ESC and then type “:x” without quotes and hit Enter.
Now to execute the file, use the following command on Linux terminal
sh sampleshift.sh

But here we have to pass command-line arguments so we can use the following
command

sh sampleshift.sh G1 G2 G3 G4

Here, we are passing 4 command-line arguments named G1, G2, G3, and G4. Below
is the screenshot of the output of using shift command:

42 | P a g e
IV. 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.

Shell functions are similar to subroutines, procedures, and functions in other programming
languages.

a) 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 −

#!/bin/sh

# Define your function here


Hello () {
43 | P a g e
echo "Hello World"
}

# Invoke your function


Hello
Upon execution, you will receive the following output −
$./test.sh
Hello World

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

#!/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

c) 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

44 | P a g e
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 −
#!/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

d) 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 −

#!/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.


45 | P a g e
number_one
Upon execution, you will receive the following result −

This is the first function speaking...


This is now the second function speaking...

e) 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

46 | P a g e

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy