shell control statements
DESCRIPTION
Shell Control Statements. CS465 - UNIX. Shell arithmetic using expr. The standard Bourne shell does not provide built-in arithmetic operators, so we have to use the expr command. Interactive example: $ num=1 $ expr $num + 1 2 $ - PowerPoint PPT PresentationTRANSCRIPT
![Page 1: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/1.jpg)
Shell Control Statements
CS465 - UNIX
![Page 2: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/2.jpg)
Shell arithmetic using expr• The standard Bourne shell does not provide built-in
arithmetic operators, so we have to use the expr command.
• Interactive example:$ num=1$ expr $num + 12$
• To assign the result of an expr command to another shell variable, surround it with backquotes:
$ sum=`expr $num + 1`$ echo $sum2$
![Page 3: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/3.jpg)
Why expr is needed
Unless otherwise indicated, all values are assumed to be STRINGS:
$ num=1
$ val=$num+1
$ echo $val
1+1
$
![Page 4: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/4.jpg)
• expr is needed to translate the variables from strings to numbers and performs the indicated math. The result is converted back to a string.
• Example:$ var1=3$ var2=5$ sum=`expr $var1 + $var2`$ echo $sum8$
Shell arithmetic using expr
Spaces around operator required
![Page 5: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/5.jpg)
expr Operators– Math operators:
+, -, *, /, % (Must use backslash with *)
– Comparison of strings (text): < , <=, =, !=, >=, > (Must use backslash with <, <=, >, >=)
– Compounds& (and), | (or)(Must use backslash with both)
![Page 6: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/6.jpg)
• Asterisk (*) is usually a wildcard character
– Must precede the asterisk with a backslash to use it for multiplication within expr.
• Example:
$ num=5$ prod=`expr $num \* 3`$ echo $prod15$
Multiplication using expr
Spaces around operator still required
![Page 7: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/7.jpg)
• expr allows you to group expressions using parentheses, but parentheses are metacharacters used to group commands
– So the “(“ and “)” characters also need to be preceded by backslashes.
• Example:
$ num=2$ echo `expr 5 \* \( $num + 3 \)`25$
Parentheses using expr
![Page 8: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/8.jpg)
$ cat test6#!/bin/sh
echo –n "Enter a number: "read numsqr=`expr $num \* $num`echo The square of $num is $sqr$
Integer restriction on expr
Floats are illegal!
test6Enter a number: 6 The square of 6 is 36$ test6Enter a number: 8.2expr: non-numeric argument$
![Page 9: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/9.jpg)
Student exercise
• Write a script that will read in your age as of Dec 31st (of this year), and then compute and display the year you were born.
![Page 10: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/10.jpg)
Exercise Sample Solution
$ cat birthyr#!/bin/shecho "Enter age on Dec 31st: \c"read agecuryr=2009birthyr=`expr $curyr - $age`echo You were born in $birthyrexit 0$ Enter age on Dec 31st: 47You were born in 1962$
![Page 11: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/11.jpg)
Bourne Shell Control Statements
• if – conditional execution of one block of commands or another
• while – repeatedly execute block of commands until condition is no longer true
• for – iterate over a list of values, executing a block of commands once for every item in the list (not directly analogous to HLL for-loops!)
• case – multi-way conditional execution
![Page 12: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/12.jpg)
The test command
$ cat check echo –n "Yes or no: " read answer test $answer = yes echo $? $ check Yes or no: yes 0 $
Use test command to evaluate logical expressions.
test assigns status 0 if the condition is true or 1 if the condition is false. Variable $? holds the status of the last test.
$ check Yes or no: no 1 $
![Page 13: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/13.jpg)
test equivalence
test condition
is equivalent to:
[ condition ]
Note space between condition & brackets!
Square brackets [ ] are used as a “shortcut” for test command:
![Page 14: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/14.jpg)
test within if statements
test is used by the if statement, to test conditions:
Again, note space betweencondition & brackets!
if test condition OR
then
action
fi
if [ condition ]
then
action
fi
![Page 15: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/15.jpg)
if statement
if [ condition ]then
command(s)
elsecommand(s)
fi
• Must have spaces between condition and square brackets
• There are no curly braces. The "true" command block extends from then to else (or fi). The "false" command block extends from else to fi.
• The else block is optional.
• "fi“, indicating the end, is "if" spelled backwards.
![Page 16: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/16.jpg)
String Conditional Tests
s1 = s2– true if strings s1 and s2 are identical
s1 != s2– true if strings s1 and s2 are not identical
-n s1– true if length of string s1 is nonzero
-z s1– true if length of string s1 is zero
![Page 17: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/17.jpg)
String Condition ExampleTask: Compare two names
$ cat namecmp#!/bin/shecho Enter 2 namesread name1 name2if [ "$name1" = "$name2" ] then
echo Same names!else
echo Different names!fi$
$ namecmpEnter 2 namesPam JoeDifferent names!$$ namecmpjoe JoeDifferent names!$
$ namecmpJoe JoeSame names!$
![Page 18: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/18.jpg)
if string details
• You don't have to use double quotes around a variable expansion, but doing so will prevent syntax errors when the variable is the null string:
• Assume an empty string: string=""
if [ "$string" = foo ] • same as if [ "" = foo ]
if [ $string = foo ]• same as if [ = foo ]This is a syntax error!
![Page 19: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/19.jpg)
Numeric Conditional Testsn1 -eq n2
– true if integers n1 and n2 are equivalentn1 -lt n2
– true if integer n1 is less than n2n1 -gt n2
– true if integer n1 is greater than n2n1 -ge n2
– true if integer n1 is greater than or equal to n2n1 -le n2
– true if integer n1 is less than or equal to n2
![Page 20: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/20.jpg)
Numeric Example #1 – no else
Task: Test to see if any arguments were passed into the script. If there were NOT, display a message.
$ argscriptNo arguments$ argscript hello$
$ cat argscript#!/bin/shif [ $# -eq 0 ] thenecho No arguments
fiexit 0$
![Page 21: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/21.jpg)
Numeric Example #2 – with elseTask: Test to see if any arguments were passed into the script. Display a message either way.
$ showargsNo arguments$ showargs Ford GM2 arguments: Ford GM$
$ cat showargs#!/bin/shif [ $# -eq 0 ] then echo No arguments
else echo $# arguments: $*
fiexit 0$
![Page 22: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/22.jpg)
Numeric Condition Example #3
$ cat calcmales#!/bin/shecho Enter number of total students:read totalecho Enter percent male \(1-100\):read percentif [ $percent -gt 100 ] then echo Percent entered is too bigelse nummale=`expr $percent \* $total / 100`
echo There are $nummale male studentsfi
$
![Page 23: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/23.jpg)
Example #3 Execution
$ calcmalesEnter number of total students:88Enter percent male (1-100):109Percent entered is too big$$ calcmalesEnter number of total students:88Enter percent male (1-100):50There are 44 male students$
![Page 24: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/24.jpg)
Student Exercise
• Modify previous script to read month and year of birth year and compute your age at the end of the current month..
![Page 25: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/25.jpg)
Exercise Sample Solution$ cat calcage#!/bin/shecho -n "Enter birth year: "read byrecho -n "Enter birth month: "read bmoncuryr=2009curmon=5age=`expr $curyr - $byr`if [ $curmon –lt $bmon ]then
age=`expr $age – 1`fiecho You will be $age at this month\’s endexit 0$ calcageEnter birth year: 1962Enter birth month: 9You will be 46 at this month’s end$
![Page 26: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/26.jpg)
Logical Conditional Operatorsexpr1 –a expr2
– AND operator between two logical conditions
expr1 –o expr2
– OR operator between two logical conditions
! expr1
– unary NOT operator before one logical condition
'(' expr1 -a expr2 ')' -o expr3– Parentheses can be used for grouping– Must use single quotes or backslash
![Page 27: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/27.jpg)
$ cat notify
#!/bin/sh
if [ `whoami` = "smith123" -o \
`whoami` = "jones456" ]
then
echo "See the system administrator! "
fi
exit 0
$ notify
$
Logical Condition Example
![Page 28: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/28.jpg)
File Conditional Tests
-r filename
• true if filename exists and is readable
-w filename
• true if filename exists and is writable
-d filename
• true if filename exists and is a directory
-s filename
• true if filename exists and is nonzero in length
NOTE: See test or sh manpage for more file conditions
![Page 29: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/29.jpg)
File Condition Example #1
Test to see if the file myprogs exists and is a directory. If so, move to the myprogs directory and list the files in it.
$ cat progdir#!/bin/shif [ -d myprogs ]then cd myprogs lsfi$ progdirfile1.c file2.c$
![Page 30: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/30.jpg)
File Condition Example #2
• Script file mvf moves to the user's home directory and prompts for a subdirectory name to move files to. It then checks to see if the named subdirectory exists. If not, the subdirectory is created. Then the files are moved to the subdirectory.
![Page 31: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/31.jpg)
File Condition Script #2
$ cat mvf#! /bin/sh# Moves parameter filenames to subdirectorycdecho Move files to which subdirectory?read subnameif [ ! -d $subname ]then echo Creating subdirectory $subname ...mkdir $subname
fimv $* $subnameecho Move complete.exit 0$
![Page 32: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/32.jpg)
File Condition Script #2 Execution
$ ls -F $HOMEmbox prog1.c prog3.cnotes\ prog2.c$ mvf prog1.c prog2.cMove files to which subdirectory?cprogsCreating subdirectory cprogs ...Move complete.$ ls -F $HOMEcprogs\ mbox notes\ prog3.c$ cd cprogs$ lsprog1.c prog2.c$
![Page 33: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/33.jpg)
Student Exercise
• Write a script which takes ONE argument, a filename. The script should check if the file exists and is readable. If it DOES, display it. If NOT, issue an error message.
![Page 34: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/34.jpg)
$ cat display#!/bin/shfile=$1if [ -r $file ]thencat $file
elseecho File $1 not readable or nonexistent!
fi$ display memoFile memo not readable or nonexistent!$
Exercise Sample Solution
![Page 35: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/35.jpg)
elif syntax (i.e.“else if”)
Can use elif to create a nested set of “if-then-else” structures.
Notice then command appears after “elif” statement.
if [ condition ]then action 1elif [ condition ]then action2else action3fi
![Page 36: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/36.jpg)
elif Example #2$ cat test8#!/bin/shusers=`who | wc -l`if [ $users -ge 10 ]
then echo "Heavy load"elif [ $users -gt 1 ]
then echo "Medium load"else
echo "Just me!"fi$ test8Medium load!$
![Page 37: Shell Control Statements](https://reader036.vdocuments.net/reader036/viewer/2022081502/56815805550346895dc5759d/html5/thumbnails/37.jpg)
elif Example # - what type is file?
#!/bin/shif [ -d what ]then echo File is a directory
lselif [ -b what ]then echo File is a block special fileelif [ -c what ]then echo File is a character special fileelif [ -a what ]then echo File exists - unknown file typeelse echo File does not existfi