Shell Scripts
Shell Scripts
Shell Scripts
Example:
echo "Do you wish List the files in the current directory?
[y/n]:"
read ans
case "$ans" in
Y | y ) ls;;
N | n) exit;;
esac
Wild-Cards: case uses them:
Example : emp12.sh and emp13.sh
• Case has string matching feature that uses wild-cards. It
uses the filename matching metacharacters *, ? and
character class.
Example:
echo "Do you wish to list the file[yes/no]"
read ans
case "$ans" in
[Yy][eE]*) ls;; # Matches YE, ye, Ye, yE, YEs, yeS, YEskdk etc
[Nn][oO]) exit;; #Matches no, NO, No, nO
*) echo “Invalid Response”
esac
Example: emp13.sh
echo "Do you wish to list the file[yes/no]"
read ans
case "$ans" in
[Yy][eE]?) ls;; # Matches YES, yes, Yes, yEs, etc
[Nn][oO]) exit;; #Matches no, NO, No, nO
*) echo “Invalid Response”
esac
expr: Computation and String
Handling
• The Broune shell uses expr command to perform computations.
This command combines the following two functions:
Performs arithmetic operations on integers
Manipulates strings
• Computation:
• expr can perform the four basic arithmetic operations (+, -, *, /), as
well as modulus (%) functions.
Examples:
$ x=3 y=5
$ expr 3+5
8
$ expr $x-$y
-2
$ expr 3 \* 5 Note:\ is used to prevent the shell from
interpreting * as metacharacter
15
$ expr $y / $x
1
$ expr 13 % 5
3
expr is also used with command substitution to assign a variable.
Example1:
$ x=6 ;y=2 ; z=`expr $x + $y`
$ echo $z
8
Example2:
$ x=5
$ x=`expr $x+1`
$ echo $x
6
String Handling:
• expr is also used to handle strings. For
manipulating strings, expr uses two expressions
separated by a colon (:). The string to be worked
upon is enclosed on the left of the colon and a
regular expression is placed on its right.
• Depending on the composition of the
expression expr can perform the following three
functions:
1. Determine the length of the string.
2. Extract the substring.
3. Locate the position of a character in a string.
Length of the string:
• The regular expression .* is used to print the number of
characters matching the pattern .
Example1:
$ expr “abcdefg” : ‘.*’
7
• Example2: emp14.sh
while echo "enter your name: "; do
read name
if [ `expr "$name" : '.*'` -gt 5 ]; then
echo "Name is very long"
else
break
fi
done
• 2. Extracting a substring:
• expr can extract a string enclosed by the escape characters \
(and \).
Example:
$ st=2007
$ expr “$st” : ’..\(..\)’ #first two .. Ignore first two next two
prints last two charaters
07 Extracts last two characters.