LP Unit II
LP Unit II
LP 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
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:
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.
#!/bin/sh
#!/bin/bash
pwd
ls
Dr. K. K. Baseer kkbaseer.moodlecloud.com 6
Cont..
Example1:
$vi test.sh
Esc :wq
$sh test.sh
/home/baseer
Type Metacharacters
Filename substitution ? * […] [!..]
I/O Redirection > < >> << m> m>&n
Process Execution ; () & && ||
Quoting metacharacters \ ““ „„ ` `
Positional parameter $1…$9
Special Character $0 $* $@ $# $! $$ $-
Example:
ls a*
ls ??
ls a?b?
ls [kdgp]*
ls [c-fmrv-z]*
ls [!d-m]*
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..
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
Predefined
User-Defined
Environmental
Shell Variables
Variables
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.
$echo $$
29949
#!/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
#!/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]}"
$./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:
-d file Check if file is a directory if yes then condition becomes true. [ -d $file ] is not 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.
-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)
Ex:
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):-
continue n
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