Unix VI Editor
Unix VI Editor
SHELL PROGRAMMING
1
INTRODUCTION
Shell script: when a group of commands have to be executed
regularly, they should be stored in a file and the file itself
executed as a shell script or, shell program
Vi Editor
You may use .sh extension but its not mandatory.
Example:
#! /bin/sh
Vi Editor
Comment lines start with #, but not for #!
The name of this file (assume) : shellscript1.sh
Now change the mode : $ chmod +x shellscript1.sh
Then execute: $ shellscript1.sh
You can also execute your program by:
MY SECOND SCRIPT
#!/bin/sh
Vi Editor
echo “ Enter the pattern to be searched: “
read pname
read flname
#! /bin/sh
Vi Editor
# command line arguments - Shellscript3.sh
grep “$1” $2
Vi Editor
$0 Name of executed command
$* Complete set of positional parameters as a
single string
“$@” Each quoted string is treated as a separate
argument
$? Exit status of last command
$$ PID of current shell
$! PID of the last background job
EXIT STATUS OF COMMAND : EXIT
Like C you can stop the execution of your shell script and exit
from the program by exit command
We normally exit by returning an argument of exit e.g.
Vi Editor
The parameter $? Stores the exit status of last executed
command. Try the following:
$ grep director emp.lst > /dev/null ; echo $?
0 [success]
$ grep CEO emp.lst > /dev/null ; echo $?
1 [Failed in finding pattern]
$ grep director emp3.lst > /dev/null ; echo $?
grep: can’t open emp3.lst
2 [Failed in finding pattern]
CONTD…
The exit status of the command are very important
Vi Editor
The programmers use the status of commands to branch their
programs
Vi Editor
$ grep ‘director’ emp.lst && echo “Pattern found in file “
Output will show the selected lines then Pattern found in file
$ grep ‘CEO’ emp.lst || echo “Pattern not found “
Output will show Pattern not found as grep is silent after not
getting any pattern
THE IF CONDITIONAL
The three forms of using if statements are as follows:
(1) if command is successful
then
execute commands
Vi Editor
else
execute commands
fi
Vi Editor
else …….
fi
#! /bin/sh
# using if else - shellscript4.sh
if grep ‘director’ emp.lst > /dev/null
then
echo “Pattern found”
else
echo “Pattern not found”
fi
USING TEST AND [ ] TO EVALUATE
EXPRESSIONS
To use if the expressions should be executed to provide truth
value; the test command is used along with if for this purpose
Vi Editor
test command uses certain operators to evaluate the
conditions and returns either with true or, false as its exit
status
test can work with the followings:
Numeric comparisons
String comparisons
Checks a file’s attributes
NUMERIC COMPARISION
$ x=5 ; y = 7 ; z = 7.2
$ test $x -eq $y ; echo $? [ans: 1
Vi Editor
$ test $x -lt $y ; echo $? [ans: 0
$ test $z -gt $y ; echo $? [ans: 1
$ test $z -eq $y ; echo $? [ans: 0
From the last two command we can conclude that the numeric
comparision is restricted to integers only
Another example : contd…
#! /bin/sh
Vi Editor
elif test $# -eq 2 ; then
else
fi
Vi Editor
-ge Greater than or equal to
-lt Less than
-le Less than or, equal to
Vi Editor
echo “ you have not entered the string” ; exit 1
fi
echo “ enter the file name to be used : “
read flname
if [ ! -n “$flname” ] ; then # ! -n is same as -z
echo “ you have not entered the file name” ; exit 2
fi
shellscript3.sh “$pname” “$flname”
else
shellscript3.sh “$pname” “$flname”
fi
CONTD…
Run the above script like: shellscript6.sh “lalit Chowdhury” emp.lst
Now replace the $* with “$@” in the above script & run
The above script can run in interactive and non-interactive modes
Vi Editor
$ shellscript6.sh
root:x:0:1:Super-User:/:/usr/bin/bash
CONTD…
test also permits the checking of more than one condition using -a
(AND) and -o (OR) operators.
The ! Operator negates the condition
Vi Editor
else
echo “at least one input was null string” ; exit 1
fi
Test True if
String test: s1 = s2 String s1 = s2
s1 != s2 String s1 is not equal to s2
-n stg String stg is not a null string
-z stg String stg is a null string
stg String is assigned and not null
FILE TESTS
#! /bin/sh
if [ ! -e $1 ] ; then
Vi Editor
echo “ file doesn’t exist “
elif [ ! -r $1 ] ; then
elif [ ! -w $1 ] ; then
Vi Editor
-w File File exists and is writable
-x File File exists and is executable
-d File File exists and is a directory
-s File File exists and the size is greater than zero
-L file File exists and is a symbolic link (Korn &
Bash only )
f1 -nt f2 f1 is newer than f2 (Korn & Bash only )
f1 -ot f2 f1 is older than f2 (Korn & Bash only )
f1 -ef f2 f1 is linked to f2 (Korn & Bash only )
THE CASE CONDITIONAL
This is a multi-way branching construct
The syntax is:
case expression in
Vi Editor
pattern1) commands ;;
pattern1) commands ;;
….
pattern n ) commands # default
esac
case can’t handle relational and file tests but it matches
strings
#! /bin/sh
# shellscript8.sh - Menu driven program
echo “ MENU\n
1. List of files \n 2. Processes of user\n 3. Today’sdate
4. Users of system \n 5. Quit to UNIX \n Enter your option: “
Vi Editor
read choice
case “$choice” in
1) ls -l ;;
2) ps -f ;;
3) date ;;
4) who ;;
5) exit ;;
*) echo “ invalid option”
esac
CONTD…
Vi Editor
y|Y) ;;
n|N) exit ;;
esac
Wild cards *, ? can be used
case “$answer” in
[yY][eE]*) ;;
[nN][oO]) exit ;;
*) echo “Invalid response”
esac
COMPUTATION AND STRING HANDLING:
EXPR
The expr command used for:
Arithmetic operations on integers
Manipulates strings
Vi Editor
Arithmetic computation:
$ x=3 y=5
$ expr 3 + 5 ; expr $x - $y ; expr 3 \* 5 ; expr $y / $x ; expr 13 % 5
$ x = 6 y = 2 ; z = ` expr $x + $y ` ; x = `expr $x + 1` #
assignment
String Handling:
Determine the length of string
Extract a substring
CONTD…
#! /bin/sh
Vi Editor
read name
$ stg = 2018
Vi Editor
$ expr “$stg” : ‘..\(..\)’
18
Locating position of a character:
4
LOOPS IN SHELL PROGRAMMING
A loop is a powerful programming tool that enables you to
execute a set of commands repeatedly.
We will examine the following types of loops available to
shell programmers
Vi Editor
While loop
For loop
Until loop
While loop syntax:
You will use different loops based on the situation. The while
loop executes the given commands until the given condition
remains true; the until loop executes until a given condition
becomes true.
WHILE LOOP
do
Commands
done
You can use any UNIX command or, test as the condition
The commands between do and done will be executed
repeatedly
Some examples:
#! /bin/sh
# shellscript10.sh - implementing while loop
answer=y
while [ “answer” = “y” ]
do
echo “enter the code and description”
Vi Editor
read code description
echo “ $ code - $description” >> newlist
echo “enter any more (y/n)?”
read anymore
case $anymore in
y*|Y*) answer=y ;;
n*|N*) answer=n ;;
*) answer=y
esac
done
NESTING OF WHILE LOOP
#!/bin/sh
# shellscript11.sh
a=0
while [ "$a" -lt 10 ] # this is loop1
do
Vi Editor
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done
OUTPUT
0
10
210
3210
Vi Editor
43210
543210
6543210
76543210
876543210
9876543210
UNTIL LOOP
#!/bin/sh
# shellscript12.sh
a=1
until [ $a -lt 10 ]
do
echo $a
a=expr `$a + 1`
done
BREAK AND CONTINUE STATEMENTS
following two statements that are used to control shell loops−
Vi Editor
The continue 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. The break command can also be
used to exit from a nested loop using this format − break n
Vi Editor
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
fi
done
done
Output: 1 0
1 5
THE CONTINUE STATEMENT
Vi Editor
given to the continue command to skip commands from
Vi Editor
do
Q=`expr $NUM % 2`
if [ $Q -eq 0 ]
then
echo “ $NUM : Number is an even number!!"
continue
fi
echo "Found odd number: $NUM"
done
OUTPUT
1234567
Vi Editor
2 : Number is an even number!!
Vi Editor
To declare a function, simply use the following syntax −
function_name ( ) {
list of commands
}
The name of your function is function_name, and it is used to call
it from elsewhere in your scripts.
EXAMPLE
#!/bin/sh
# shellscript15.sh
# Define your function here
Hello ( ) {
Vi Editor
echo "Hello World"
}
output −
Hello World
PASS PARAMETERS TO A FUNCTION
You can define a function that will accept parameters while
calling the function. These parameters would be represented
by $1, $2 and so on.
#!/bin/sh
Vi Editor
# shellscript16.sh
# Define your function here
Hello ( ) {
echo "Hello $1 $2"
}
# Invoke your function
Hello Sharda University
Output:
Hello Sharda University
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.
Vi Editor
Based on the situation you can return any value from your function
using the return command whose syntax is as follows: return x
#!/bin/sh
# shellscript17.sh
Hello ( ) {
echo "Hello $1 $2"
return 10
}
Hello Sharda University # Invoke your function
Vi Editor
ret=$?
Output:
Vi Editor
}
number_two ( ) {
echo "This is now the second function speaking..."
}
number_one # Calling function one.
Output:
This is the first function speaking...
This is now the second function speaking...
REMOVING DEFINITION OF A FUNCTION
Vi Editor
to remove the definition of a variable to the shell.
$ unset .f function_name
END OF UNIT-5
Vi Editor