Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
159 views

Shell Programming Module2 Part2

This document provides an overview of shell programming. It defines what a shell is and describes that shells understand user commands and carry them out. It discusses that shell programming involves grouping commands into scripts and using programming constructs to control the sequence and flow. It also covers reasons for shell programming like executing commands regularly or in a specific order. Finally, it provides examples of basic shell scripts, using command line arguments, reading user input, and checking command exit statuses.

Uploaded by

HIMANK MISHRA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
159 views

Shell Programming Module2 Part2

This document provides an overview of shell programming. It defines what a shell is and describes that shells understand user commands and carry them out. It discusses that shell programming involves grouping commands into scripts and using programming constructs to control the sequence and flow. It also covers reasons for shell programming like executing commands regularly or in a specific order. Finally, it provides examples of basic shell scripts, using command line arguments, reading user input, and checking command exit statuses.

Uploaded by

HIMANK MISHRA
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 120

Essential Shell Programming

By
Prashanth Kumar K N
Assistant Professor
Department of Computer Science & Engineering
BIT, Bangalore
Objective
• What is Shell Programming
• Need for Shell Programming
• Shell Programming Variants
• Writing some Scripts
Basics
Definition:
Shell is an agency that sits between the user and
the UNIX system.

Description:
• Understands all user directives and carries them
out.
• Processes the commands issued by the user.
• Type of shell called Bourne shell.
What is Shell Programming
• Grouping a set commands
A shell is a command-line interpreter and typical operations
performed by shell scripts include file manipulation,
program execution, and printing text.

• Programming constructs used


Shell scripts have several required constructs that tell the shell
environment what to do and when to do it.
Need for Shell Programming
• To execute a set of commands regularly
• Typing every time every command is laborious
& time consuming
• To have control on the sequence of commands
to be executed based previous results
Shell Scripts/Shell Programs
• Group of commands have to be executed
regularly stored in a file
• File itself executed as a shell script or a shell
program by the user.

• A shell program runs in interpretive mode.

• Shell scripts are executed in a separate child shell


process which may or may not be same as the
login shell.
Shell Scripts
Example: script1.sh
#! /bin/sh
# script.sh: Sample Shell Script
echo “Welcome to Shell Programming”
echo “Today’s date : `date`”
echo “This months calendar:”
cal `date “+%m 20%y”` #This month’s calendar.
echo “My Shell :$SHELL”
Sample shell script
The following script uses the read command which takes the
input from the keyboard and assigns it as the value of the
variable PERSON and finally prints it on STDOUT.

#!/bin/sh
# Script follows here:
echo "What is your name?"
read PERSON
echo "Hello, $PERSON"
Here is a sample run of the script −

$./test.sh
What is your name?
Prashanth Kumar K N
Hello, Prashanth Kumar K N
$
Shell Scripts
• To run the script we need to first make it
executable. This is achieved by using the
chmod command as shown below:

• $ chmod +x script1.sh
• Then invoke the script name as:
• $ ./script1.sh
Shell Scripts
• Explicitly spawn a child with script name as
argument:

• sh script1.sh

• Note: Here the script neither requires a


executable permission nor an interpreter line.
Read: Making Scripts Interactive
• Shell’s internal tool for making scripts interactive
• Used with one or more variables.
• Inputs supplied with the standard input are read
into these variables.
• Ex: read name
• causes the script to pause at that point to take
input from the keyboard.
Shell script to read input from stdin
#!/bin/bash

echo -n "Enter some text > "


read text
echo "You entered: $text"

Output:
Enter some text > Welcome to UNIX Class
You entered: Welcome to UNIX Class
read
• The read command has several command line options.
The three most interesting ones are -p, -t and -s
• The -p option allows us to specify a prompt to precede the
user's input. This saves the extra step of using an echo to
prompt the user.
#!/bin/bash
#read -p "Enter some text > " text
#echo "You entered: $text"
Output:

Enter some text > welcome


You entered: welcome
• The -t option followed by a number of seconds provides
an automatic timeout for the read command. This means
that the read command will give up after the specified
number of seconds if no response has been received from
the user

#!/bin/bash

echo -n "Hurry up and type something! > "


read -t 3 response

echo "Sorry, you are too slow!"


• The -s option causes the user's typing not to be displayed.
This is useful when we are asking the user to type in a
password or other confidential information

#!/bin/bash

echo -n "Enter some text > "


read -s text
echo "You entered: $text"

Output:
Enter some text > You entered: welcome
The shell can perform a variety of arithmetic operations
#!/bin/bash

first_num=0
second_num=0

read -p "Enter the first number --> " first_num


read -p "Enter the second number -> " second_num

echo "first number + second number = $((first_num + second_num))"


echo "first number - second number = $((first_num - second_num))"
echo "first number * second number = $((first_num * second_num))"
echo "first number / second number = $((first_num / second_num))"
echo "first number % second number = $((first_num % second_num))"
echo "first number raised to the"
echo "power of the second number = $((first_num ** second_num))"
Shell Script that formats an arbitrary number of
seconds into hours and minutes

#!/bin/bash
seconds=0
read -p "Enter number of seconds > " seconds
hours=$(seconds / 3600)
seconds=$((seconds % 3600))
minutes=$((seconds / 60))
seconds=$((seconds % 60))
echo "$hours hour(s) $minutes minute(s) $seconds second(s)"

Output:
Enter number of seconds > 40000
11 hour(s) 6 minute(s) 40 second(s)
Shell Script to read first, middle and last name
#!/bin/bash
read -p "Please Enter first word followed by ENTER: " first
read -p "Please Enter second word followed by ENTER: " middle
read -p "Please Enter last word followed by ENTER: " last
echo "Hello $first $middle $last"

Output:
Please Enter first word followed by ENTER: Rahul
Please Enter second word followed by ENTER: Sharad
Please Enter last word followed by ENTER: Dravid
Hello Rahul Sharad Dravid
Shell Script to read number of variables
#!/bin/bash
read -p "Please Enter some words followed by ENTER: " vara
varb varc
echo "vara contains $vara"
echo "varb contains $varb"
echo "varc contains any remaining words $varc"
Output:
Please Enter some words followed by ENTER: one two three
four five
vara contains one
varb contains two
varc contains any remaining words three four five
Read: Making Scripts Interactive
Example: A shell script that uses read to take a search string
and filename from the terminal.
#! /bin/sh
# script2.sh: Interactive version, uses read to accept two inputs
echo -e “Enter the pattern to be searched: \c” # No newline
read pname
echo -e “Enter the file to be used: \c”
read fname
echo “Searching for pattern $pname from the file $fname”
grep “$pname” $fname
echo “Selected records shown above”
Read: Making Scripts Interactive
Output:
$ sh script2.sh
Enter the pattern to be searched: director
Enter the file to be used: emp.lst
Searching for pattern director from the file emp.lst
1006|Prashanth Kumar| director|sales|03/10/2020|50000
1008|Pramod | director|marketing|24/10/2020|40000
1006|Prakash | director|sales|27/10/2020|70000
1006|Praveen | director|sales|03/10/2020|60000
Selected records shown above
Using Command Line Arguments
• Shell scripts accept arguments from the
command line.
• Run non interactively
• Arguments are assigned to special shell
variables (positional parameters).
• Represented by $1, $2, etc;
Using Command Line Arguments
Using Command Line Arguments
#emp2.sh Non-interactive version -uses command line
arguments
#! /bin/sh
echo “Program Name : $0”
echo “No of Arguments specified is : $#”
echo “The Arguments are : $*”

$ chmod +x emp2.sh

$ emp2.sh A B C
o/p🡪 Program Name : emp2.sh
No of Arguments : 3
Arguments are : A B C
Using Command Line Arguments
#emp3.sh Non-interactive version -uses command line arguments
#! /bin/sh
echo “Program Name : $0”
echo “The number of arguments specified is : $#”
echo “The arguments are : $*”
grep “$1” $2
echo “Job Over\n”

Program Name : emp3.sh


The number of arguments specified is : 2
The arguments are : director emp.lst
1006|Prashanth Kumar| director|sales|03/10/2020|50000
1008|Pramod | director|marketing|24/10/2020|40000
1006|Prakash | |sales|27/10/2020|70000
Job Over
example on command line arguments
#!/bin/sh
echo “ shell script on command line arguments
echo "Username: $1";
echo "Age: $2";
echo "Full Name: $3";
Output:
$ sh 1.sh prashanth 38 prashanthkumar
Username: prashanth
Age: 38
Full Name: prashanthkumar
Example on command line arguments
#!/bin/bash
echo "Positional Parameters"
echo '$0 = ' $0
echo '$1 = ' $1
echo '$2 = ' $2
echo '$3 = ' $3

Output:
$ sh 1.sh a b c
Positional Parameters
$0 = 1.sh
$1 = a
$2 = b
$3 = c
exit and Exit Status of Command
• To terminate a program, exit is used.
• Nonzero value indicates an error condition.
Example 1:
$ cat foo
cat: can’t open foo
• Returns non zero exit status.
• The shell offers a variable $? and a command
(test) that evaluate a command’s exit status.
exit and Exit Status of Command
The Parameter $?
• Stores the exit status of the last command.

• It has a value 0 if the command succeeds and

a nonzero value if it fails


• This parameter is set by exit’s argument

$echo $?
1
Example 2:
$grep director emp.lst > /dev/null;echo $?
0 Success ///dev/null is a special file called the null device in Unix systems
//because it immediately discards anything written to it and only returns an end-of-file EOF when
read.

$grep manager emp.lst>/dev/null; echo $?


1 Failure in finding pattern

$grep manager emp3.lst>/dev/null; echo $?


grep: can’t open emp3.lst Failure in opening file
2
• Exit status is used to devise program logic that branches
into different paths depending on success or failure of a
command
The logical Operators && and ||
• Two operators that allow conditional execution,
the && and ||.
• Usage:
cmd1 && cmd2
cmd1 || cmd2

• && delimits two commands. cmd 2 executed only


when cmd1 succeeds.
The logical Operators && and ||
Example1:
$ grep "director" emp.lst && echo "Pattern found"
1006|Prashanth Kumar|
director|sales|03/10/2020|50000
1008|Pramod |
director|marketing|24/10/2020|40000
1006|Prakash | director|sales|27/10/2020|70000
1006|Praveen | director|sales|03/10/2020|60000
Pattern found
The logical Operators && and ||
Example 2:
$ grep ‘clerk’ emp.lst || echo “Pattern not
found”
Output:
Pattern not found
The if Conditional
Form 1 Form 2 Form 3
if command is successful if command is successful if command is successful
then then then
execute commands execute commands execute commands
fi else elif command is successful
execute commands then...
fi else...
fi

• If the command succeeds, the statements within if


are executed or else statements in else block are
executed (if else is present).
The if Conditional
Example:
#! /bin/sh
#emp3.sh: Using if and else
if grep “^$1” /etc/passwd 2>/dev/null
# ^ matching at the beginning of the line
then
echo “Pattern Found”
else
echo “Pattern Not Found”
fi
The if Conditional
Output1:
$ sh emp3.sh ftp
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
Pattern Found

Output2:
$ sh emp3.sh mail
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
mailnull:x:47:484::/var/spool/mqueue:/sbin/nologin
Pattern Found
Using test and [ ] to Evaluate
Expressions
• test statement is used to handle the true or
false value returned by expressions.
• test uses certain operators to evaluate the
condition on its right
• Returns either a true or false exit status
• It is used by if conditional for making
decisions.
Using test and [ ] to Evaluate
Expressions
test works in three ways:
• Compare two numbers
• Compares two strings or a single one for a
null value
• Checks files attributes
test doesn’t display any output but simply returns a
value that sets the parameters $?
Using test and [ ] to Evaluate
Expressions
Numeric Comparison:
Using test and [ ] to Evaluate
Expressions
Numeric Comparison:
Example:
$ x=5;y=7;z=7.2
$ test $x –eq $y; echo $?
1 Not equal

$ test $x –lt $y; echo $?


0 True
$ test $z -gt $y; echo $?
0 True
Using test and [ ] to Evaluate
Expressions
Shorthand for test

● [ and ] can be used instead of test.


● The following two forms are equivalent
test $x –eq $y
and
[ $x –eq $y ]
Using test and [ ] to Evaluate
Expressions
String Comparison
Shell script example
#!/bin/sh
#emp3a.sh using test, $0 and $# in an if-elif-if construct
if test $# -eq 0; then
echo "Usage: $0 pattern file">>/dev/tty
elif test $# -eq 2; then
grep "$1" $2 || echo "$1 is not found in $2">/dev/tty
else
echo "You didn't enter two arguments">/dev/tty
fi

Output:
sh emp3a.sh director emp.lst
1006|Prashanth Kumar| director|sales|03/10/2020|50000
1008|Pramod | director|marketing|24/10/2020|40000
1006|Prakash | director|sales|27/10/2020|70000
1006|Praveen | director|sales|03/10/2020|60000
Script uses the if statement and the test [ command to check if
the strings are equal or not with the = operator

#!/bin/bash
VAR1="BIT"
VAR2="CSE"

if [ “$VAR1" = "$VAR2" ]; then


echo "Strings are equal."
else
echo "Strings are not equal."
fi
script that takes the input from the user and
compares the given strings

#!/bin/bash

read -p "Enter first string: " VAR1


read -p "Enter second string: " VAR2

if [ "$VAR1" == "$VAR2" ]; then


echo "Strings are equal."
else
echo "Strings are not equal."
fi
File Tests
• test can be used to test various file attributes
like its type (file, directory or symbolic links) or
its permission (read, write. Execute, SUID, etc).
Example:
$ ls –l emp.lst
-rw-rw-rw- 1 kumar group 870 jun 8 15:52 emp.lst
$ [-f emp.lst] ; echo $?
0 🡪 Ordinary file
File Tests
$ [-x emp.lst] ; echo $? 🡪 Not an executable.
1
$ [ -w emp.lst] || echo “False that file is not
writeable”
False that file is not writable.
File Tests
Using test and [ ] to Evaluate Expressions
Example:
#!/bin/sh
#emp11.sh checks user input for null values finally turns emp.sh developed previously
#
if [ $# -eq 0 ] ; then
echo -e “Enter the string to be searched :\c”
read pname
if [ -z “$pname” ] ; then # to check the string is not a null string
echo “You have not entered the string”; exit 1
fi
echo -e “Enter the filename to be used :\c”
read flname
if [ -z “$flname” ] ; then # to check the string is not a null string
echo “ You have not entered the filename” ; exit 2
fi
grep “$pname” $flname
fi
Using test and [ ] to Evaluate Expressions
Output1:
$sh emp11.sh
Enter the string to be searched :[Enter]
You have not entered the string

Output2:
sh emp11.sh
Enter the string to be searched :director
Enter the filename to be used : [Enter]
You have not entered the filename
Using test and [ ] to Evaluate Expressions
Output3:
$ sh emp11.sh
Enter the string to be searched :director
Enter the filename to be used :emp.lst

1006|Prashanth Kumar| director|sales|03/10/2020|50000


1008|Pramod | director|marketing|24/10/2020|40000
1006|Prakash | director|sales|27/10/2020|70000
1006|Praveen | director|sales|03/10/2020|60000
script that accepts filename and
perform number of tests on it
#!/bin/sh
#filetest.sh: Tests file attributes
if [ ! -e $1 ] ;then
echo -e “ File does not exist”
elif [ ! -r $1 ] ;then
echo -e “ File is not readable”
elif [ ! -w $1 ] ;then
echo -e “ File is not writable”
else
echo -e “ File is both readable and writable”
fi
The case Conditional
• Conditional statement offered by the shell
• The statement matches an expression for
more than one alternative, and uses a
compact construct to permit multiway
branching.
• Also handles string tests, but in a more
efficient manner than if.
The case Conditional

Syntax:

case expression in
Pattern1) commands1 ;;
Pattern2) commands2 ;;
Pattern3) commands3 ;;

esac
The case Conditional
Example: case.sh
#! /bin/sh
echo -e “Menu\n
1. List of files\n 2. Processes of user\n
3. Today’s Date
4. Users of system\n 5.Quit\n
Enter your option: \c”
read choice
case “$choice” in
1) ls ;;
2) ps ;;
3) date ;;
4) who ;;
5) exit ;;
*) echo “Invalid option”
esac
The case Conditional
Output
$ menu.sh
Menu
1. List of files
2. Processes of user
3. Today’s Date
4. Users of system
5. Quit
The case Conditional
Enter your option: 1
1.sh emp11.sh emp2.sh emp3.sh emp.sh~
read.sh~ script1.sh
1.sh~ emp11..sh~ emp2.sh~ emp3.sh~

Enter your option: 3


Mon Oct 8 08:02:45 IST 2007
shell script on case statement
#!/bin/bash
# if no command line arg given # set rental to Unknown
if [ -z $1 ] # -z stg test string stg is a null string
then
rental="*** Unknown vehicle ***"
elif [ -n $1 ] # -n stg test string stg is not a null string
then
# otherwise make first arg as a rental
rental=$1
fi

# use case statement to make decision for rental


case $rental in
"car") echo "For $rental rental is Rs.20 per k/m.";;
"van") echo "For $rental rental is Rs.10 per k/m.";;
"jeep") echo "For $rental rental is Rs.5 per k/m.";;
"bicycle") echo "For $rental rental 20 paisa per k/m.";;
"enfield") echo "For $rental rental Rs.3 per k/m.";;
"thunderbird") echo "For $rental rental Rs.5 per k/m.";;
*) echo "Sorry, I can not get a $rental rental for you!";;
esac
The case Conditional
Matching Multiple Patterns:
• case can also specify the same action for more than
one pattern .
• For instance to test a user response for both y and
Y (or n and N).
Example: mult.sh
echo -e “Do you wish to continue? [y/n]: \c”
read ans
case “$ans” in
Y | y );; # Null statement, no action to be performed
N | n) exit ;;
esac
The case Conditional

Output1:
$sh mult.sh
Do you wish to continue? [y/n]: y
$

Output2:
sh mult.sh
Do you wish to continue? [y/n]: n
$
The case Conditional
Wild-Cards: case uses them
• case has a superb string matching feature
that uses wild-cards.
• It uses the filename matching
metacharacters *, ? and character class (to
match only strings and not files in the
current directory).
The case Conditional
Example:
case “$ans” in
[Yy] [eE]* );; Matches YES, yes, Yes, yEs, etc
[Nn] [oO]) exit ;; Matches no, NO, No, nO
*) echo “Invalid Response”
esac
Shell script on multiple pattern
#!/bin/bash
NOW=$(date +"%a") # date + %a gives weekday
case $NOW in
Mon)
echo "Full backup";;
Tue|Wed|Thu|Fri)
echo "Partial backup";;
Sat|Sun)
echo "No backup";;
*) ;;
esac
shell script demonstrate the concept of command line parameters
processing using the case statement (casecmdargs.sh)
#!/bin/bash
OPT=$1 # option
FILE=$2 # filename
# test -e and -E command line args matching
case $OPT in
-e|-E)
echo "Editing $2 file..." # make sure filename is passed else an error displayed
[ -z $FILE ] && { echo "File name missing"; exit 1; } || vi $FILE
;;
-c|-C)
echo "Displaying $2 file..."
[ -z $FILE ] && { echo "File name missing"; exit 1; } || cat $FILE
;;
-d|-D)
echo "Today is $(date)"
;;
*)
echo "Bad argument!"
echo "Usage: $0 -ecd filename"
echo " -e file : Edit file."
echo " -c file : Display file."
echo " -d : Display current date and time."
;;
esac
expr: Computation and String Handling

● The Bourne shell uses expr command to


perform computations and string manipulation.

● expr is an external command

● expr can perform the four basic arithmetic


operations (+, -, *, /), as well as modulus (%)
functions.
expr contd..
Computation:
Example1 :$ x=3 y=5
$ expr $x+$y
8 🡪 Output

Example 2: $expr $x -$y


-2

Example 3:$ expr 3 \* 5


15 🡪 Output
Example 4: $ expr $y/$x
1 Decimal part truncated
Example 5: $ expr 13 %5
3

Note: \ is used to prevent the shell from interpreting * as metacharacter


expr contd..
• expr is also used with command substitution to
assign a variable.

Example: $x=5
$x=`expr $x+1`
$echo $x
6 🡪Output
expr contd.. String Handling
• For manipulating strings, expr uses two
expressions separated by a colon (:)

• expr can perform the following three functions:


→ Determine the length of the string
→ Extract the substring
→ Locate the position of a character in a string
expr contd..
Length of the string:
The regular expression .* is used to print the
number of characters matching the pattern .
Example: $expr “abcdefg” : ‘.*’ (o/p 🡪 7)
Extracting a substring:
expr can extract a string enclosed by the escape
characters \ (and \).
Example:$ stg=2007
$ expr “$stg” :’..\(..\)’ Extracts last two
characters
(o/p 🡪 07)
expr contd..
Locating position of a character:
• expr can return the location of the first
occurrence of a character inside a string.

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

(o/p 🡪4)
$0: Calling a Script by Different Names

• There are a number of UNIX commands that can


be used to call a file by different names and
doing different things depending on the name by
which it is called.

• Similarly $0 can also be used to call a script by


different names.
Contd..
Example: expr.sh
#! /bin/sh
lastfile=`ls –t *.c | head –n 1` # -t sort by modification time
command=$0
exe=`expr $lastfile: ‘\(.*\).c’`
case $command in
*runc) $exe ;;
*vic) vi $lastfile ;;
*comc) cc –o $exe $lastfile &&
echo “$lastfile compiled successfully” ;;
esac
Contd..
After this create the following three links:
ln comc.sh comc
ln comc.sh runc
ln comc.sh vic

Output:
$ comc
hello.c compiled successfully.
While: Looping
● To carry out a set of instruction repeatedly shell
offers three features namely while,for and until.

Syntax:
while condition is true
do Note the do keyword
commands
done Note the done keyword
Contd..
Example:
#! /bin/usr
ans=y # Must set it to y first to enter the loop
while [“$ans”=”y”]
do
echo -e “Enter the code and description : \c” > /dev/tty
read code description # Read both together
Contd..
echo “$code $description” >>newlist # append a line to newlist
echo “Enter any more [Y/N]” >/dev/tty
read any
case $any in
Y* | y* ) answer =y;;
N* | n*) answer = n;;
*) answer=y;;
esac
done
Contd..

Output:
Enter the code and description : 03 analgestics
Enter any more [Y/N] :y
Enter the code and description : 04 antibiotics
Enter any more [Y/N] : n
Contd..
Output:
$ cat newlist
03 | analgestics
04 | antibiotics

newlist opened only once with


done> newlist
All command output inside loop will go to
newlist. To avoid this use /dev/tty
While: Looping

Input:
Enter the code and description : 03 analgestics
Enter any more [Y/N] :y
Enter the code and description : 04 antibiotics
Enter any more [Y/N] : [Enter]
Enter the code and description : 05 OTC drugs
Enter any more [Y/N] : n
While: Looping
Output:
$ cat newlist
03 | analgestics
04 | antibiotics
05 | OTC drugs
for: Looping with a List
for is also a repetitive structure.
Syntax:
for variable in list
do
commands
done
Note: list here comprises a series of character
strings. Each string is assigned to variable
specified.
Contd..

Example: $ for file in ch1 ch2; do


> cp $file ${file}.bak
> echo $file copied to $file.bak
done

Output: ch1 copied to ch1.bak


ch2 copied to ch2.bak
Contd..
Sources of list:
1. List from variables:
Series of variables are evaluated by the shell
before executing the loop

Example: $ for var in $PATH $HOME;


>do echo “$var” ; done

Output: /bin:/usr/bin;/home/local/bin;
/home/user1
Contd..
2. List from command substitution:
Command substitution is used for creating a list.
This is used when list is large.
Example: $ for var in `cat clist` ;do
> echo ‘$var’ ;done

3. List from wildcards:


Here the shell interprets the wildcards as
filenames.
Contd..
Example: for file in *.htm *.html ; do
sed ‘s/strong/STRONG/g
s/img src/IMG SRC/g’ $file > $$
mv $$ $file
done

4. List from positional parameters:


for is also used to process positional parameters
that are assigned from command line
Contd..
Example: emp.sh
#! /bin/sh
for pattern in “$@”; do
grep “$pattern” emp.lst || echo “Pattern $pattern not
found”
done
Output: $ emp.sh 9876 “Rohit”
9876 Jai Sharma DirectorProductions
2356 Rohit DirectorSales
While: Looping Varieties
Wait for a file
#! /bin/sh
While [! –r invoice.lst] do
Sleep 60
done
echo “file created”
While: Looping Varieties
Infinite loop
While true ; do
df –t
Sleep 300
done &
basename: Changing Filename Extensions

• They are useful in changing the extension of


group of files.
• basename extracts the “base” filename from an
absolute pathname.
Example1: $basename /home/user1/test.pl
Output: test.pl

Example2: $basename test2.doc doc


Output: test2
set and shift: Manipulating the Positional
Parameters

● The set statement assigns positional parameters


$1, $2 and so on, to its arguments.

● This is used for picking up individual fields from


the output of a program.
set and shift: Manipulating the Positional
Parameters
Example 1: $ set 9876 2345 6213

● This assigns the value 9876 to the positional


parameters $1, 2345 to $2 and 6213 to $3
Example2:
● we can verify this by echoing each parameter as
below
$ echo “\$1 is $1, \$2 is $2, \$3 is $3”
$1 is 9876, $2 is 2345, $3 is 6213
• We now use command substitution to extract
individual fields from the date output without
using cut

$set `date`
$ echo $*
Tue Oct 27 11:59:27 IST 2020

$echo -e “The date today is $2, $3, $6”


The date today is Oct, 27, 2020
Shift: Shifting Arguments Left
● Shift transfers the contents of positional
parameters to its immediate lower numbered
one.
Example 1:
$ echo “$@” Here @ and $* are interchangeable
Mon Oct 8 08:02:45 IST 2007

$ echo $1 $2 $3
Mon Oct 8
Shift: Shifting Arguments Left

$ shift
$ echo $1 $2 $3
Oct 8 08:02:45

$ shift 2
08:02:45 IST 2007
Shift: Shifting Arguments Left
#!/bin/sh
case $# in
0|1) exit 2;;
*) $fname = $1
shift
for pattern in “$@”; do
grep “$pattern” $fname || echo “$pattern
not found”
done;;
esac
Set -- : Helps Command Substitution

• In order for the set to interpret - and null output


produced by UNIX commands the – option is
used .

• If not used – in the output is treated as an option


and set will interpret it wrongly. In case of null, all
variables are displayed instead of null.
Contd..
Example1: $set `ls –l chp1`
Output: -rwxr-xr-x: bad options
Example2: $set `grep usr1 /etc/passwd`

Correction to be made to get correct output are:


$set -- `ls –l chp1`
$set -- `grep usr1 /etc/passwd`
The Here Document (<<)
• The shell uses the << symbol to read data from
the same file containing the script.
–Here document.
• Signifying that the data is here rather than in a
separate file.
• Any command using standard input can also take
input from a here document.
• A here document is used to redirect input into an interactive shell script or
program.
• We can run an interactive program within a shell script without user action
by supplying the required input for the interactive program, or interactive
shell script.
• The general form for a here document is −
command << delimiter
document
delimiter

• Here the shell interprets the << operator as an instruction to read input until
it finds a line containing the specified delimiter. All the input lines up to the
line containing the delimiter are then fed into the standard input of the
command.
• The delimiter tells the shell that the here document has completed. Without
it, the shell continues to read the input forever. The delimiter must be a
single word that does not contain spaces or tabs.
Examples on here document
$ wc -l <<EOF
BIT college
Department of CSE
Bengaluru
EOF

Output:
3
Examples on here document
#!/bin/sh
cat << EOF
BIT
CSE Dept.
EOF

Output:
BIT
CSE Dept.
The Here Document (<<)
Example:
mailx kumar << MARK
Your program for printing the invoices has been executed
on `date`.Check the print queue
The updated file is $flname
MARK
● The Here document symbol(<<) is followed by three lines of
data and a delimiter
● The shell treats each line following the command and
delimited by MARK as input to the command
● sharma at the other end will see the three lines of message
text with the date inserted by the command substitution
and the evaluated filename
The Here Document (<<)
Using Here Document with Interactive Programs:
● A shell script can be made to work
non-interactively by supplying inputs through
here document.
Example:
$ sh emp.sh << END
> director
>emp.lst
>END
The Here Document (<<)
Output:
Enter the pattern to be searched: Enter the file to
be used: Searching for director from file emp.lst

9876 Jai sharma Director Productions


2356 Rohit Director Sales
Selected records shown above.
trap: interrupting a Program
• By default, shell scripts terminate whenever the
interrupt key is pressed.
• It’s not always a good idea to terminate shell script in
this way because that can leave a lot of temporary files
on disk.
• The trap statement lets you do the things you want to
do when a script receives a signal.
• The statement is normally placed at the beginning of
the shell script and uses two lists:
trap ‘command_list’ signal_list
trap: interrupting a Program
● When a script is sent any of the signals in
signal_list, trap executes the commands in
command_list.
● The signal list can contain the integer values or
names (without SIG prefix) of one or more
signals – the ones used with the kill command.
● Example: To remove all temporary files named
after the PID number of the shell:
trap: interrupting a Program
trap ‘rm $$* ; echo “Program Interrupted” ; exit’
HUP INT TERM

● trap is a signal handler.


● Removes all files expanded from $$*, echoes a
message and finally terminates the script when
signals SIGHUP (1), SIGINT (2) or SIGTERM(15)
are sent to the shell process running the script.
trap: interrupting a Program

● A script can also be made to ignore the signals


by using a null command list.

Example:
trap ‘ ‘1 2 15
Shell Script on trap
#!/bin/bash
# capture an interrupt # 0
trap 'echo "exit 0 signal detected..."' 0

# display something
echo "This is a test"

# exit shell script with 0 signal


exit 0
● The first line sets a trap when script tries to
exit with status 0.
● Then script exits the shell with 0, which
would result in running echo command.

Output:
This is a test
exit 0 signal detected...
● Try the following example at a shell prompt (make sure sample.txt doesn't
exist).
● Define a shell variable called $file:
file=prashanth.txt

Now, try to remove $file, enter:


rm $file

Sample output:
rm: cannot remove `prashanth.txt': No such file or directory
Now sets a trap for rm command:
trap "rm $file; exit" 0 1 2 3 15

Display list of defined traps, enter:


trap

Sample outputs:
trap -- 'rm prashanth.txt; exit' EXIT
trap -- 'rm prashanth.txt; exit' SIGHUP
trap -- 'rm prashanth.txt; exit' SIGINT
trap -- 'rm prashanth.txt; exit' SIGQUIT
trap -- 'rm prashanth.txt; exit' SIGTERM
Shell Script on trap command
#!/bin/bash
# capture an interrupt # 2 (SIGINT)
trap '' 2
# read CTRL+C from keyboard with 30 second timeout
read -t 30 -p "I'm sleeping hit CTRL+C to exit..."

Output:
I'm sleeping hit CTRL+C to exit...^C^C^C^C
Debugging shell scripts with set -x
$ emp.sh emp.lst 22 12 01
+flname=emp.lst
+shift
+grep 22 emp.lst
22 shekar gm sales 12/08/07
+grep 12 emp.lst
12 xyz director marketing 15/10/07
Sample scripts
#!/bin/sh
IFS=“|”
While echo “enter dept code:\c”; do
Read dcode
Set -- `grep “^$dcode”<<limit
01|ISE|22
02|CSE|45
03|ECE|25
04|TCE|58
limit`
Sample scripts
Case $# in
3) echo “dept name :$2 \n emp-id:$3\n”
*) echo “invalid code”;continue
esac
done
Sample scripts
Output:
$valcode.sh
Enter dept code:88
Invalid code
Enter dept code:02
Dept name : CSE
Emp-id :45
Enter dept code:<ctrl-c>
Sample scripts

#!/bin/sh
x=1
while [$x –le 10];do
echo “$x”
x=`expr $x+1`
done
Sample scripts
#!/bin/sh
sum=0
for I in “$@” do
echo “$I”
sum=`expr $sum + $I`
done
Echo “sum is $sum”
Sample scripts
#!/bin/sh
sum=0
for I in `cat list`; do
echo “string is $I”
x= `expr “$I”:’.*’`
Echo “length is $x”
done

You might also like