You are on page 1of 76

UNIT-II

SHELL PROGRAMMING
• Necessity of Shell Programming
• Pipes and I/O Redirection (|, <, >, and <<)
• Redirecting Output
• Redirecting Input
• Pipes
• The Shell as a Programming Language
• Interactive Programs
• Creating a Script
• Making a Script Executable
• Shell Syntax:
 Variables
 Conditions
 Control Structures
 Functions
 Commands
 Command Execution
Shell Types

In UNIX there are two major types of shells:

 The Bourne shell. If you are using a Bourne-type shell, the


default prompt is the $ character.

 The C shell. If you are using a C-type shell, the default prompt
is the % character.

There are again various subcategories for Bourne Shell which are
listed as follows:

 Bourne shell (sh)


 Korn shell (ksh)
 Bourne Again shell (bash)
 POSIX shell (sh)

The different C-type shells follow:


 C shell ( csh) (Bill Joy)
 TENEX/TOPS C shell ( tcsh) 2
Dr. K. K. Baseer kkbaseer.moodlecloud.com
Cont..

 The original UNIX shell was written in the mid-1970s by


Stephen R. Bourne while he was at AT&T Bell Labs in New
Jersey.
 The Bourne shell was the first shell to appear on UNIX
systems, thus it is referred to as "the shell".
 The Bourne shell is usually installed as /bin/sh on most
versions of UNIX. For this reason, it is the shell of choice for
writing scripts to use on several different versions of UNIX.

Dr. K. K. Baseer kkbaseer.moodlecloud.com 3


Figure. Bourne shell
Shell Scripts

 The basic concept of a shell script is a list of commands, which


are listed in the order of execution. A good shell script will have
comments, preceded by a pound sign, #, describing the steps.

 There are conditional tests, such as value A is greater than


value B, loops allowing us to go through massive amounts of
data, files to read and store data, and variables to read and
store data, and the script may include functions.

 Shell scripts and functions are both interpreted. This means


they are not compiled.

Dr. K. K. Baseer kkbaseer.moodlecloud.com 5


Example Script: Cont..

 Assume we create a test.sh script. Note all the scripts would


have .sh extension. Before you add anything else to your
script, you need to alert the system that a shell script is being
started. This is done using the shebang construct.

 For example:

 This tells the system that the commands that follow are to
be executed by the Bourne shell. It's called a shebang
because the # symbol is called a hash, and the ! Symbol
is called a bang.

 To create a script containing these commands, you put the


shebang line first and then add the commands:

#!/bin/sh
#!/bin/bash
pwd
ls
Dr. K. K. Baseer kkbaseer.moodlecloud.com 6
Cont..
Example1:

$vi test.sh

# An interactive shell script


echo What is your name\?
read name
echo Hello $name. Happy Programming

Esc :wq

$sh test.sh

What is your name?


kkbaseer
Hello kkbaseer. Happy Programming

Dr. K. K. Baseer kkbaseer.moodlecloud.com 7


Example2:
Cont..
$vi example1.sh
#!/bin/bash
pwd
ls

/home/baseer

3a.sh Desktop f5 filetail joinfile Public


3b.sh Documents file1 filetail1 joinfile1
sample.awk census Downloads file10 filetee
karthik sree censusamp example1.sh file11 filetee1 kkb
Templates censusflash f1 file2 filetr1 kkb1 test.sh
censusnew f2 file3 gr linesort total.dat
censustab f2.txt file4 input.dat linesortnew trfile
censusunique f3 filecpio j1 Music Videos
censusuniquenew f4 filecpio1 j2 Pictures

Dr. K. K. Baseer kkbaseer.moodlecloud.com 8


UNIT-II
SHELL PROGRAMMING
• Necessity of Shell Programming
• Pipes and I/O Redirection (|, <, >, and <<)
• Redirecting Output
• Redirecting Input
• Pipes
• The Shell as a Programming Language
• Interactive Programs
• Creating a Script
• Making a Script Executable
• Shell Syntax:
 Variables
 Conditions
 Control Structures
 Functions
 Commands
 Command Execution
All Metacharacters

Type Metacharacters
Filename substitution ? * […] [!..]
I/O Redirection > < >> << m> m>&n
Process Execution ; () & && ||
Quoting metacharacters \ ““ „„ ` `
Positional parameter $1…$9
Special Character $0 $* $@ $# $! $$ $-

Dr. K. K. Baseer kkbaseer.moodlecloud.com 10


Cont..

Filename substitution ? * […] [!..]

Example:
ls a*
ls ??
ls a?b?
ls [kdgp]*
ls [c-fmrv-z]*
ls [!d-m]*

Dr. K. K. Baseer kkbaseer.moodlecloud.com 11


Cont..

I/O Redirection > < >> << m> m>&n


> Standard output
< Std input
>> Append
<< Next operator (Here Document)
m>filename Makes filename the output of m
m>&n Merges the std output and std
error if m=1 and n=2. Here m
and n denote file descriptors.
They can take the values 0, 1 or
2 representing standard input,
std output and std error resp.

Dr. K. K. Baseer kkbaseer.moodlecloud.com 12


Cont..

Example:
[baseer@localhost ~]$ cat file1
IT-A
[baseer@localhost ~]$ cat file1>out_here
[baseer@localhost ~]$ cat out_here
IT-A
[baseer@localhost ~]$ cat file2
Congratulations!!
[baseer@localhost ~]$ cat file2>>out_here [cat<file2>>out_here]
[baseer@localhost ~]$ cat out_here
IT-A
Congratulations!!
Dr. K. K. Baseer kkbaseer.moodlecloud.com 13
Cont..

[baseer@localhost ~]$ cat <<bye


> hello
> how are you
> i am studing in SVEC
> bye
hello
how are you
i am studing in SVEC
[baseer@localhost ~]$ time ls > myfile 2>&1

Dr. K. K. Baseer kkbaseer.moodlecloud.com 14


[m>filename]
[baseer@localhost ~]$ sh example5.sh
example5.sh: line 3: print: command not found
example5.sh: line 4: ..............: command not found
File Name: example5.sh
First Parameter :
second Parameter :
Third Parameter:
Quoted Values:
Quoted Values:
Total Number of Paramers : 0
[baseer@localhost ~]$ sh example5.sh 2>errors
File Name: example5.sh
First Parameter :
second Parameter :
Third Parameter:
Quoted Values:
Quoted Values:
Total Number of Paramers : 0
[baseer@localhost ~]$ cat errors
example5.sh: line 3: print: command not found
example5.sh: line 4: ..............: command not found
[baseer@localhost ~]$
Dr. K. K. Baseer kkbaseer.moodlecloud.com 15
Process Execution ; () & && ||
[baseer@localhost ~]$ pwd;ls;date
[baseer@localhost ~]$ (cd Pictures;pwd)
/home/baseer/Pictures
[baseer@localhost ~]$ pwd
/home/baseer
[baseer@localhost ~]$ cd Pictures;pwd
/home/baseer/Pictures
[baseer@localhost Pictures]$ pwd
/home/baseer/Pictures
[baseer@localhost ~]$ ps&
[1] 3044
[baseer@localhost ~]$ PID TTY TIME CMD
2410 pts/0 00:00:00 bash
3044 pts/0 00:00:00 ps
[1]+ Done ps 16
UNIT-II
SHELL PROGRAMMING
• Necessity of Shell Programming
• Pipes and I/O Redirection (|, <, >, and <<)
• Redirecting Output
• Redirecting Input
• Pipes
• The Shell as a Programming Language
• Interactive Programs
• Creating a Script
• Making a Script Executable
• Shell Syntax:
 Variables
 Conditions
 Control Structures
 Functions
 Commands
 Command Execution
Unix - Using Shell 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.
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 would have their names in
UPPERCASE.
The following examples are valid & invalid variable names:
abc -var
_abc 2abc
var1 abc!
var_1 Var-1
The reason you cannot use other characters such as! ,*, or - is
that these characters have a special meaning for the shell. 1
Dr. K. K. Baseer kkbaseer.moodlecloud.com 8
Defining Variables Cont..
Variables are defined as follows::
Variable_name=variable_value
For example:
NAME="SVEC"
Above example defines the variable NAME and assigns it the value
"SVEC". Variables of this type are called scalar variables.
A scalar variable can hold only one value at a time. The shell enables
you to store any value you want in a variable. For example:

VAR1="xyz"
VAR2=100
Accessing Values: To access the value stored in a variable, prefix its
name with the dollar sign ( $): For example, following script would
access the value of defined variable NAME and would print it on
STDOUT:
#!/bin/sh
NAME="SVEC"
echo $NAME 1
This would produce following value: SVEC 9
Cont..
Shell keywords

echo if until trap


read else case wait
set fi esac eval
unset while break exec
readonly do continue ulimit
shift done exit umask
export for return

Dr. K. K. Baseer kkbaseer.moodlecloud.com 20


Read-only Variables: Cont..
The shell provides a way to mark variables as read-only by using
the readonly command. After a variable is marked read-only, its
value cannot be changed.
For example, following script would give error while trying to
change the value of NAME:
Example3:
#!/bin/sh
NAME="SVEC"
readonly NAME
NAME="SVIS"
This would produce following result:
/bin/sh: NAME: This variable is read only.

Dr. K. K. Baseer kkbaseer.moodlecloud.com 21


Cont..
Unsetting Variables: Unsetting or deleting a variable tells the
shell to remove the variable from the list of variables that it
tracks. Once you unset a variable, you would not be able to
access stored value in the variable. Following is the syntax to
unset a defined variable using the unset command:
unset variable_name
Above command would unset the value of a defined variable.
Here is a simple example:
Example4:
#!/bin/sh
NAME="SVEC"
unset NAME
echo $NAME
Above example would not print anything. You cannot use the
unset command to unset variables that are marked readonly.

Dr. K. K. Baseer kkbaseer.moodlecloud.com 22


Variable Types: Cont..

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

 Environment Variables: An environment variable is a variable


that 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.
Dr. K. K. Baseer kkbaseer.moodlecloud.com 23
Variables Cont..

Predefined
User-Defined

Environmental
Shell Variables
Variables

Dr. K. K. Baseer kkbaseer.moodlecloud.com 24


Environmental Variables Cont..

Variable Meaning
PS1 System Prompt 1
Ex: $PS1=“IT-A”
IT-A instead of $ prompt
PS2 The system prompt 2, default value is “>”
PATH Defines the path which the shell must search in order to
execute any command or file
HOME Stores the default working directory of the user. On entering
just a cd, the system understands that HOME is where we
want to go and we are back to our default directory.

LOGNAME Stores the login name of the user


MAIL Defines the file, where the mail of the user is stored.
IFS Define the Internal Field Separator, which is a space, a tab
or a newline
SHELL Defines the name of your default working shell
TERM Defines the name of the terminal on which you are working

TZ Defines the name of the time zone in which we are working 25


Cont..

UNIX - Special Variables

Above command would write PID of the current shell:


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

$echo $$

29949

Dr. K. K. Baseer kkbaseer.moodlecloud.com 26


Variable Description Cont..

$0 The filename of the current script.


These variables correspond to the arguments with which a
script was invoked. Here n is a positive decimal number
$n
corresponding to the position of an argument (the first
argument is $1, the second argument is $2, and so on).
$# The number of arguments supplied to a script.
All the arguments are double quoted. If a script receives
$*
two arguments, $* is equivalent to $1 $2.

All the arguments are individually double quoted. If a


$@
script receives two arguments, $@ is equivalent to $1 $2.

The exit status of the last command executed. (0


$?
successful and 1 unsuccessful)

The process number of the current shell. For shell scripts,


$$
this is the process ID under which they are executing.

$! The process number of the last background command. 27


Example5: Cont..

#!/bin/sh
echo "File Name: $0"
echo "First Parameter : $1"
echo "First Parameter : $2"
echo "Quoted Values: $@"
echo "Quoted Values: $*"
echo "Total Number of Paramers : $#"
Here is a sample run for the above script:
$sh test.sh abc xyz
File Name : test.sh
First Parameter :abc
First Parameter :xyz
Quoted Values: abc xyz
Quoted Values: abc xyz
Total Number of Paramers : 2
Dr. K. K. Baseer kkbaseer.moodlecloud.com 28
Cont..
Special Parameters $* and $@:
 There are special parameters that allow accessing all of the
command-line arguments at once. $* and $@ both will act
the same unless they are enclosed in double quotes, "".
 Both the parameter specifies all command-line arguments
but 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 shown below to process an
unknown number of command-line arguments with either the $*
or $@ special parameters:
There is one sample run for the above script:
Example6 $sh test.sh he is 10 Years Old
#!/bin/sh he
for TOKEN in $* is
do 10
echo $TOKEN Years
Done Old
Dr. K. K. Baseer kkbaseer.moodlecloud.com 29
Examples on readonly, unset, set, $? And other commands
Cont..
[baseer@localhost ~]$ a=30
[baseer@localhost ~]$ readonly a
[baseer@localhost ~]$ echo $a
30
[baseer@localhost ~]$ a=40
bash: a: readonly variable
[baseer@localhost ~]$ unset a
bash: unset: a: cannot unset: readonly variable

[baseer@localhost ~]$ set hai how are you


[baseer@localhost ~]$ echo $1 $2
hai how
Example7:
cp $1 $2 [baseer@localhost ~]$ sh example7.sh f1 f2
cat $1 fhf
chmod 744 $1 gj
ls –li $1 .............
271819 -rwxr--r--. 1 baseer baseer 7 Dec
26 22:37 f1
Dr. K. K. Baseer kkbaseer.moodlecloud.com 30
Unix - Using Shell Arrays:

• A shell variable is capable enough to hold a single value. This


type of variables is called scalar variables.

• Shell supports a different type of variable called an array


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

Dr. K. K. Baseer kkbaseer.moodlecloud.com 31


Defining Array Values: Cont..
• The difference between an array variable and a scalar variable can be
explained as follows.
• Say that 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:
• We can use a single array to store all the above mentioned names.
Following is the simplest method of creating an array variable is to
assign a value to one of its indices. This is expressed as follows:
• 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:
• If you are using bash shell the here is the syntax of array initialization:
NAME01="Zara"
NAME02="Qadir"
array_name[index]=value
NAME03="Mahnaz"
NAME04="Ayan"
NAME05="Daisy" NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz" array_name=(value1 ... valuen)
NAME[3]="Ayan" 32
NAME[4]="Daisy"
Accessing Array Values: Cont..
• After you have set any array variable, you access it as follows:
• Here array_name is the name of the array, and index is the
index of the value to be accessed. Following is the simplest
example:
${array_name[index]}

#!/bin/sh
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"

This would produce following result:

$./test.sh
First Index: Zara
Second Index: Qadir 33
Cont..
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 is the simplest example:

#!/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[@]}"

$sh test.sh
First Method: Zara Qadir Mahnaz Ayan Daisy
Second Method: Zara Qadir Mahnaz Ayan Daisy 34
Unix - Shell Basic Operators
There are various operators supported by each shell. There are
following operators which we are going to discuss:
• Arithmetic Operators.
• Relational Operators.
• Boolean Operators.
• String Operators.
• File Test Operators.
The Bourne shell didn't originally have any mechanism to
perform simple arithmetic but it uses external programs, either
awk or the must simpler program expr.
Here is simple example to add two numbers:
#!/bin/sh
val=`expr 2 + 2`
echo "Total value : $val“
This would produce following result: Total value : 4
There are following points to note down:
• There must be spaces between operators and expressions for
example 2+2 is not correct, where as it should be written as
2 + 2.
• Complete expression should be enclosed between ``, called35
inverted commas.
Arithmetic Operators: Cont..
There are following arithmetic operators 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


+ `expr $a + $b` will give 30
the operator
Subtraction - Subtracts right hand
- `expr $a - $b` will give -10
operand from left hand operand
Multiplication - Multiplies values on
* `expr $a * $b` will give 200
either side of the operator
Division - Divides left hand operand by
/ `expr $b / $a` will give 2
right hand operand
Modulus - Divides left hand operand by
% right hand operand and returns `expr $b % $a` will give 0
remainder
Assignment - Assign right operand in a=$b would assign value of b
=
left operand into a
Equality - Compares two numbers, if [ $a == $b ] would return
==
both are same then returns true. false.
Not Equality - Compares two numbers, [ $a != $b ] would return 36
!=
if both are different then returns true. true.
Relational Operators: Cont..
Operator Description Example

Checks if the value of two operands are


-eq equal or not, if yes then condition [ $a -eq $b ] is not true.
becomes true.
Checks if the value of two operands are
-ne equal or not, if values are not equal then [ $a -ne $b ] is true.
condition becomes true.
Checks if the value of left operand is
-gt greater than the value of right operand, [ $a -gt $b ] is not true.
if yes then condition becomes true.
Checks if the value of left operand is less
-lt than the value of right operand, if yes [ $a -lt $b ] is true.
then condition becomes true.
Checks if the value of left operand is
greater than or equal to the value of
-ge [ $a -ge $b ] is not true.
right operand, if yes then condition
becomes true.
Checks if the value of left operand is less
than or equal to the value of right
-le [ $a -le $b ] is true.
operand, if yes then condition becomes
true.
Dr. K. K. Baseer kkbaseer.moodlecloud.com 37
Boolean Operators: Cont..

Operator Description Example

This is logical negation. This


! inverts a true condition into false [ ! false ] is true.
and vice versa.
This is logical OR. If one of the
[ $a -lt 20 -o $b -gt 100 ] is
-o operands is true then condition
true.
would be true.
This is logical AND. If both the
operands are true then condition [ $a -lt 20 -a $b -gt 100 ] is
-a
would be true otherwise it would false.
be false.

Dr. K. K. Baseer kkbaseer.moodlecloud.com 38


String Operators: Cont..
There are following string operators supported by Bourne Shell.
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 yes [ $a = $b ] is not true.
then condition becomes true.
Checks if the value of two
operands are equal or not, if
!= [ $a != $b ] is true.
values are not equal then
condition becomes true.
Checks if the given string operand
-z size is zero. If it is zero length [ -z $a ] is not true.
then it returns true.

Checks if the given string operand


-n size is non-zero. If it is non-zero [ -z $a ] is not false.
length then it returns true.
Check if str is not the empty
Str string. If it is empty then it [ $a ] is not false.
returns false.
Dr. K. K. Baseer kkbaseer.moodlecloud.com 39
File Test Operators: Cont..
There are following operators to test various properties associated with a
Unix file.
Assume a variable file holds an existing file name "test" whose size is 100
bytes and has read, write and execute permission on:
Operator Description Example

Checks if file is a block special file if yes then condition


-b file [ -b $file ] is false.
becomes true.
Checks if file is a character special file if yes then condition
-c file [ -b $file ] is false.
becomes true.

-d file Check if file is a directory if yes then condition becomes true. [ -d $file ] is not true.

Check if file is an ordinary file as opposed to a directory or


-f file [ -f $file ] is true.
special file if yes then condition becomes true.

-r file Checks if file is readable if yes then condition becomes true. [ -r $file ] is true.

-w file Check if file is writable if yes then condition becomes true. [ -w $file ] is true.

-x file Check if file is execute if yes then condition becomes true. [ -x $file ] is true.

Check if file has size greater than 0 if yes then condition


-s file [ -s $file ] is true.
becomes true.

-e file Check if file exists. Is true even if file is a directory but exists. [ -e $file ] is true.
Dr. K. K. Baseer kkbaseer.moodlecloud.com 40
Unix - Shell Decision Making (Conditions)

(a)The if-then-fi statement


(b)The if-then-else-fi statement
(c)The if-then-elif-else-fi statement
(d) The case-esac statement

Dr. K. K. Baseer kkbaseer.moodlecloud.com 41


The if-then-fi statement Cont..
Syntax:
if [ expression ] # if control command
then
Statement(s) to be executed if expression is true
fi
Here Shell expression is evaluated. If the resulting value is
true, given statement(s) are executed. If expression is false
then no statement would be not executed. Most of the times
you will use comparison operators while making decisions.

Ex:

echo "Enter source and target file names"


read source target
if cp $source $target
then
echo file copied csuccessfully
fi
Dr. K. K. Baseer kkbaseer.moodlecloud.com 42
Cont..
The if-then-else-fi statement

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
Example:
Flowchart:
Write a shell scripts to cover all Relational operators
Write a shell scripts to cover all file test operator
Write a shell scripts to cover all string conditions
Dr. K. K. Baseer kkbaseer.moodlecloud.com 43
The if-then-elfi-else-fi statement (Nested if-else) Cont..

Syntax:

if [ expression ]
then
Statement(s) to be executed if expression is true
else if control command
then
do this
else
do this and this
fi
fi
Flowchart
Write a shell scripts using logical operators
Dr. K. K. Baseer kkbaseer.moodlecloud.com 44
The case-esac statement Cont..
Syntax:
1. The basic syntax of the case...esac statement is to give an
expression to evaluate and several different statements to
execute based on the value of the expression.
2. 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
;;
*)
do this
;;
Esac

Flowchart 45
Example1: Cont..
case $num in Example4:
1) Echo you entered in case $1 in
;; cat | dog)….
2)……
;; Example5:
*)… case $char in
;; [a-z])….;;
[0-9])….;;
Example2:
case $num in
121)…….
;;
7)….
;;
Example3:
case $1 in
dog)….
;;
cat)…..
;;
Dr. K. K. Baseer kkbaseer.moodlecloud.com 46
Unix - Shell Loops (Control Structures):-

Loops are a powerful programming tool that enables you to execute


a set of commands repeatedly.
Loop definition:

The following types of loops available to shell programmers:


(a) A for loop statement
(b) A while loop statement
(c) A until loop statement

Dr. K. K. Baseer kkbaseer.moodlecloud.com 47


Cont..

The for loop:


The for loop operate 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.
Flowchart:
Dr. K. K. Baseer kkbaseer.moodlecloud.com 48
Example1:
for word in High on a hill was a lovely mountain
do
echo $word
done
Example2: read from command line arguments
for word in $* [for word]
do
echo $word
done
Example3:
Example4:
for entry in *
for entry in *.c
do
do
if [ -d $entry ]
mv $file $file.cpp
then
done
echo $entry
fi
done

Dr. K. K. Baseer kkbaseer.moodlecloud.com 49


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 control command
do
Statement(s) to be executed if command is true
done

here Shell command is evaluated. If the resulting value is true,


given statement(s) are executed. If command is false then no
statement would be not executed and program would jump to
the next line after done statement.
Examples:
while [ $# -le 5 ]
while who | grep $logname
while [ -r $file –a –w $file ] 50
Dr. K. K. Baseer kkbaseer.moodlecloud.com
Examples
1. Write a shell script to calculate SI using while loop
2. Write a shell script to print sum of n numbers using while loop
3. Write a shell script which checks after every one minute
whether your friend has logged in or not
4. Write a shell script that reads each line in a file and displays it
on the screen using while loop
5. Write a shell script to count number of lines and words supplied
at standard input using while loop

Dr. K. K. Baseer kkbaseer.moodlecloud.com 51


The until 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:
Until control command doesn‟t return true
do
this
and this……
done

 Here Shell command is evaluated. If the resulting value is


false, given statement(s) are executed. If command is true
then no statement would be not executed and program would
jump to the next line after done statement.
Examples:
until [ $# -le 5 ]
until who | grep $logname
Dr. K. K. Baseer until [ -r $file –a –w $file ] kkbaseer.moodlecloud.com 52
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.
[break n]
Example: #!/bin/sh
#!/bin/sh for var1 in 1 2 3
a=0 do
while [ $a -lt 10 ] for var2 in 0 5
do do
echo $a if [ $var1 -eq 2 -a $var2 -eq 0 ]
if [ $a -eq 5 ] then
then break 2
break else
fi echo "$var1 $var2"
a=`expr $a + 1` fi
Done done
done
This will produce 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 inner loop as
53
well.
Syntax: Continue

Like with the break statement, an integer argument can be given to


the continue command to skip commands from nested loops.
Continue
Here n specifies the nth enclosing loop to continue from.

continue n

Dr. K. K. Baseer kkbaseer.moodlecloud.com 54


UNIT-II
SHELL PROGRAMMING
• Necessity of Shell Programming
• Pipes and I/O Redirection (|, <, >, and <<)
• Redirecting Output
• Redirecting Input
• Pipes
• The Shell as a Programming Language
• Interactive Programs
• Creating a Script
• Making a Script Executable
• Shell Syntax:
 Variables
 Conditions
 Control Structures
 Functions
 Commands
 Command Execution
Functions
function_name ()
{
statements
}
A Simple Function:
#!/bin/sh
foo() {
echo “Function foo is executing”
}
echo “script starting” Output:
foo script starting
Function foo is executing
echo “script ended” script ending
exit 0
Returning a Value
echo “Original parameters are
$*“
if yes_or_no “$1”
then
echo “Hi $1, nice name”
else
#!/bin/sh
echo “Never mind”
yes_or_no() {
fi
echo “Is your name $* ?”
exit 0
while true
do
echo -n “Enter yes or no: “
read x
$ ./my_name Rick Neil case “$x” in
Original parameters are Rick Neil y | yes ) return 0;;
Is your name Rick ? n | no ) return 1;;
Enter yes or no: yes
* ) echo “Answer yes or no”
Hi Rick, nice name
$
esac
done
}
UNIT-II
SHELL PROGRAMMING
• Necessity of Shell Programming
• Pipes and I/O Redirection (|, <, >, and <<)
• Redirecting Output
• Redirecting Input
• Pipes
• The Shell as a Programming Language
• Interactive Programs
• Creating a Script
• Making a Script Executable
• Shell Syntax:
 Variables
 Conditions
 Control Structures
 Functions
 Commands
 Command Execution
break
The : Command
The colon command is a null command. It‟s occasionally useful to simplify
the logic of conditions, being an alias for true. Since it‟s built-in, : runs
faster than true, though its output is also much less readable.
#!/bin/sh
rm -f fred
if [ -f fred ]; then
:
else
echo file fred did not exist
fi
exit 0
Continue
The . Command
The dot (.) command executes the command in the current shell
Echo
eval
The eval command enables you to evaluate arguments.
foo=10
x=foo
y=‟$‟$x
echo $y
This gives the output $foo. However,
foo=10
x=foo
eval y=‟$‟$x
echo $y
gives the output 10. Thus, eval is a bit like an extra $: It gives
you the value of the value of a variable.
exec
• The exec command has two different uses. Its typical use is
to replace the current shell with a different program.
For example:
exec wall “Thanks for all the fish”
in a script will replace the current shell with the wall command.
No lines in the script after the exec will be processed, because
the shell that was executing the script no longer exists.
• The second use of exec is to modify the current file
descriptors:
exec 3< afile
This causes file descriptor three to be opened for reading from
file afile. It‟s rarely used.
exit n
• The exit command causes the script to exit with exit code n.
• In shell script programming, exit code 0 is success, and codes
1 through 125, inclusive, are error codes that can be used by
scripts.
export
The export command makes the variable named as its parameter
available in subshells.
export2: Output:
#!/bin/sh $ ./export1
The second meta-syntactic variable
echo “$foo” $
echo “$bar”

Now for export1. At the end of this script, invoke export2:


#!/bin/sh
foo=”The first meta-syntactic variable”
export bar=”The second meta-syntactic variable”
export2
expr
The expr command evaluates its arguments as an expression.
x=`expr $x + 1`

• The `` (backtick) characters make x take the result of


executing the command expr $x + 1.

You could also write it using the syntax $( ) rather than


backticks, like this:
x=$(expr $x + 1)
printf
The printf command is available only in more recent shells.
printf “format string“ parameter1 parameter2 ...

• $ printf “%s\n” hello


hello
• $ printf “%s %d\t%s” “Hi There” 15 people
Hi There 15 people

return
The return command causes functions to return, as mentioned
when we looked at functions earlier.
set
• The set command sets the parameter variables for the shell. It
can be a useful way of using fields in commands that output
space-separated values.
#!/bin/sh
echo the date is $(date)
set $(date)
echo The month is $2
exit 0

shift
• The shift command moves all the parameter variables down
by one, so that $2 becomes $1, $3 becomes $2, and so on.
The previous value of $1 is discarded, while $0 remains
unchanged.
trap
The trap command is used to specify the actions to take on
receipt of signals.
trap command signal
unset
• The unset command removes variables or functions from the
environment. It can‟t do this to read-only variables defined
by the shell itself, such as IFS. It‟s not often used.
#!/bin/sh
foo=”Hello World”
echo $foo
unset foo
echo $foo
UNIT-II
SHELL PROGRAMMING
• Necessity of Shell Programming
• Pipes and I/O Redirection (|, <, >, and <<)
• Redirecting Output
• Redirecting Input
• Pipes
• The Shell as a Programming Language
• Interactive Programs
• Creating a Script
• Making a Script Executable
• Shell Syntax:
 Variables
 Conditions
 Control Structures
 Functions
 Commands
 Command Execution
• Note that with the older form of the command execution, the
backtick, or backquote, (`), is used, not the single quote
(„) that we used in earlier shell quoting (to protect against
variable expansion). Use this form for shell scripts only when
you need them to be very portable.
• All new scripts should use the $(...) form, which was
introduced to avoid some rather complex rules covering the
use of the characters $, `, and \ inside the backquoted
command.
• The result of the $(command) is simply the output from the
command. Note that this isn‟t the return status of the
command but the string output, as shown here:

#!/bin/sh
echo The current directory is $PWD
echo The current users are $(who)
exit 0

• If you want to get the result into a variable, you can just
assign it in the usual way:

whoisthere=$(who)
echo $whoisthere
Arithmetic Expansion
A newer and better alternative is $((…)) expansion.
#!/bin/sh
x=0
while [ “$x” -ne 10 ]; do
echo $x
x=$(($x+1))
done
exit 0

Note:
The double parentheses are used for arithmetic substitution. The
single parentheses form shown earlier is used for executing
commands and grabbing the output.
Parameter Expansion
foo=fred
echo $foo

A problem occurs when you want to append extra characters


to the end of a variable. Suppose you want to write a short script
to process files called 1_tmp and 2_tmp.
#!/bin/sh
#!/bin/sh for i in 1 2
for i in 1 2 do
my_secret_process ${i}_tmp
do done
my_secret_process $i_tmp
done

But on each loop, you‟ll get the following:


my_secret_process: too few arguments
Debugging a script
 Tracing the flow of control
 Examining values of variables
 Checking whether the variable, filename and command
substitution is being done properly or not etc.
To do this, add set –vx at the beginning of the script
where v: ensures that each line in the shell script is displayed
before it gets executed
x: ensures that the command along with the argument
values that it may have is also displayed before execution.
Example:
set -vx
echo enter your name
read name
echo $name
set kkb gum samson
echo $1 $2 $3

Dr. K. K. Baseer kkbaseer.moodlecloud.com 75


Practice Programs
a. Write a Shell Script to print all .txt files and .c files.
b. Write a Shell Script to move a set of files to a specify
directory.
c. Write a Shell Script to display all the users who are currently
logged in after a specified time.
d. Write a Shell Script to wish the user based on the login time.

Dr. K. K. Baseer kkbaseer.moodlecloud.com 76

You might also like