Shell Programming Module2 Part2
Shell Programming Module2 Part2
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.
#!/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
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:
#!/bin/bash
#!/bin/bash
Output:
Enter some text > You entered: welcome
The shell can perform a variety of arithmetic operations
#!/bin/bash
first_num=0
second_num=0
#!/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”
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.
$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.
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
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"
#!/bin/bash
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
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~
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
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 (:)
(o/p 🡪4)
$0: Calling a Script by Different Names
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
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..
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
$set `date`
$ echo $*
Tue Oct 27 11:59:27 IST 2020
$ 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
• 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
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"
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
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
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