0% found this document useful (0 votes)
113 views

Unix VI Editor

The document discusses shell scripting. Some key points: 1) Shell scripts allow storing commands in a file to execute them regularly. They can be run with the sh interpreter. 2) Shell scripts use parameters like $1, $2 to access command line arguments. Operators like -eq test conditions. 3) Control structures like if/then, case allow conditional execution. Tests on files and strings are also possible. Exit statuses are used to control flow.

Uploaded by

Sabin Khadka
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views

Unix VI Editor

The document discusses shell scripting. Some key points: 1) Shell scripts allow storing commands in a file to execute them regularly. They can be run with the sh interpreter. 2) Shell scripts use parameters like $1, $2 to access command line arguments. Operators like -eq test conditions. 3) Control structures like if/then, case allow conditional execution. Tests on files and strings are also possible. Exit statuses are used to control flow.

Uploaded by

Sabin Khadka
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT-5

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

# my first shell script

echo “Today’s date: `date` ”

echo “The calendar: `cal` ”

echo “My shell : $SHELL”


EXECUTION OF SHELL SCRIPT
 The first line is interpreter line, begins with #!,
followed by the path name of the shell to be used for
running the script

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

# taking input from keyboard- shellscript2.sh

Vi Editor
echo “ Enter the pattern to be searched: “

read pname

echo “Enter the file to be used: ”

read flname

echo “searching for $pname from file $fname”

grep “$pname” $fname

echo “selected records shown above”


USING COMMAND LINE ARGUMENTS
 The unix commands also accept command line arguments like C
 The arguments in command line are assigned to positional
parameters : $1, $2 …

#! /bin/sh

Vi Editor
# command line arguments - Shellscript3.sh

echo “Program: $0 \n The no of arguments specified: $# \n

The arguments are : $* ”

grep “$1” $2

echo “\n job over “


 Execute the above program by giving the following command:

$ shellscript3.sh director emp.lst


CONTD…
Shell parameter Significance
$1, $2 …. $9 Positional parameters representing
command line
$# No of arguments specified in command line

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.

exit 0 [used when everything is fine ]


exit 1 [used when something went wrong ]

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

 To find out whether a command executed successfully or, not,


simply use echo $?, the 0 indicates success or, true, any non
integer quantity indicates failure or, false
THE LOGICAL OPERATORS : && AND ||
 The syntax of using && and || with two commands are:
 cmd1 && cmd2 [ cmd2 executes only when cmd1 succeeds]
 cmd1 || cmd2 [ cmd2 executes only when cmd1 fails]

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

(2) if command is successful


then
execute commands
fi
(3) if command is successful
then
execute commands
elif command is successful
then ……

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

# use test –shellscript5.sh

if test $# -eq 0 ; then

echo “Usage : $0 pattern file” > /dev/tty

Vi Editor
elif test $# -eq 2 ; then

grep “$1” $2 || echo “$1 not found in $2” > /dev/tty

else

echo “you didn’t enter two arguments “ > /dev/tty

fi

Run the above program in three different ways: $ shellscript.sh ,

$ shellscript.sh khajan , $ shellscript.sh khajan /etc/passwd


CONTD…
Operator Meaning
-eq Equal to
-ne Not equal to
-gt Greater than

Vi Editor
-ge Greater than or equal to
-lt Less than
-le Less than or, equal to

 The short form of test is to use the command with in [ ] ,e.g.


 test $x -eq $y can be written as [ $x -eq $y ]
 Now the test with if statements can be written as : if [ $x -gt
STRING COMPARISION

# checks user input – shellscript6.sh


if [ $# -eq 0 ] ; then
echo “ enter the string to be searched: “
read pname
if [ -z “$pname” ] ; then # - z for null string

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

Enter the string to be searched: [enter ]

You have not entered the string


 $ shellscript6.sh

Enter the string to be searched: root

Enter the file name to be used: /etc/passwd

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

 if [ -n “$pname” -a -n “$flname” ] ; then

Shellscript3.sh “$pname” “$flname”

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

#shellscript7.sh : tests fileattributes

if [ ! -e $1 ] ; then

Vi Editor
echo “ file doesn’t exist “

elif [ ! -r $1 ] ; then

echo “ file is not readable “

elif [ ! -w $1 ] ; then

echo “ file is not writable “


else
echo “ file is both readable and writable”
fi
CONTD…
 You can compare various file attributes using test by using:
Test True if file
-f File File exists and is a regular file
-r File File exists and is readable

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…

 Matching multiple patterns:


echo “ Do you wish to continue ? (y/n) :”
read answer
case “$answer” in

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

# shellscript9.sh - expr to count length of string

while echo “ Enter your name: “ ; do #echo always return true

Vi Editor
read name

if [ `expr “$name” : ‘.*’` -gt 20 ] ; then

echo “Name too long “


else
break # terminates the loop
fi
done
Another example :
$ expr “abcdef” : ‘.*’ # output is 6
CONTD…
 Extracting a sub string:

$ stg = 2018

Vi Editor
$ expr “$stg” : ‘..\(..\)’
18
 Locating position of a character:

$ stg = abcdefgh ; expr “$stg” : ‘[^d]*d’

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

while condition is true

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−

The break statement

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

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


NESTED FOR LOOP WITH BREAK
#!/bin/sh
# shellscript13.sh
for var1 in 1 2 3
do
for var2 in 0 5

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

 Similar to C programming continue is used

 Like with the break statement, an integer argument can be

Vi Editor
given to the continue command to skip commands from

nested loops : continue n

 Here n specifies the nth enclosing loop to continue from.


Example
#!/bin/sh
# shellscript14.sh
NUMS="1 2 3 4 5 6 7"
for NUM in $NUMS

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

Found odd number : 1

Vi Editor
2 : Number is an even number!!

Found odd number : 3

4: Number is an even number!!

Found odd number : 5

6 : Number is an even number!!

Found odd number : 7


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.

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"
}

# Invoke your function


Hello

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

# Capture value returned by last command

Vi Editor
ret=$?

echo "Return value is $ret"

Output:

Hello Sharda University


Return value is 10
#!/bin/sh
# shellscript18.sh
# Calling one function from another
number_one ( ) {
echo "This is the first function speaking..."
number_two

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

 To remove the definition of a function from the shell, use the

unset command with the .f option. This command is also used

Vi Editor
to remove the definition of a variable to the shell.

$ unset .f function_name
END OF UNIT-5

Vi Editor

You might also like