You are on page 1of 19

Loops

Three Forms
• while ... do ... done • until ... do ... done • for ... do ... done

Arithmetic Evaluation using let
Syntax:

let expression or (( expression ))
Examples $ x=10

$ y=2
$ let x=x+2 $ echo $x $ let “x=x / (y+1)” *double quotes are necessary to escape the special meaning of the parenthesis

Using (( )) around the expression replaces using the let. The operators recognized by the shell are listed below, in decreasing order of precedence.
OPERATOR DESCRIPTION

! * / % + <= >= <> == != =

Unary minus
Logical negation Multiplication, division, remainder Addition, subtraction Relational comparison Equals, does not equal Assignment

$ (( x = x + 1 ))

$ echo $x
$ x=12 $ let “x < 10” $ echo $? if (( x > 10 )) then echo x is greater

else
echo x is not greater fi

The while construct
Repeat the loop while the condition is true
while cond

do
list B done The while construct is a looping mechanism provided by the shell that will continue looping through the body of commands (list B) while a condition is true.

Example:
x=1 while (( x <= 10 )) do

echo hello x is $x
let x=x+1 done

Examples: (while)
ans=yes while

[ “$ans” = yes ]
do echo Enter a name

read name
echo $name >> file.names echo “continue?” echo Enter yes or no read ans done

Cont.
while (( $# != 0 )) do if test –d $1 then echo contents of $1: ls –F $1 fi shift echo there are $# items echo left on the cmd line. done

The until construct
Syntax: until cond do list B done

The until construct is another looping mechanism provided by the shell that will continue looping through the body of commands (list B) until a condition is true.

Example:
X=1
until (( X > 10))

do
echo hello X is $X let X=X+1

done

Examples: until (Repeat until ans is no)
ans=yes until [ “$ans” = no ] do echo Enter a name read name echo $name >> file.names echo “continue?” echo Enter yes or no read ans done

(Repeat until there are no command line arguments)
until (( $# == 0 )) do if test –d $1 then echo contents of $1: ls –F $1 fi shift echo there are $# items echo left on the cmd line. done

The for construct
for var in list
do list A done

Example: for
for X in 1 2 3 4 5
do

echo “2 * $X is \c”
let X=X*2

echo $X
done

Examples:
for NAME in $(grep home /etc/passwd | cut –f1 –d:) do mail NAME < mtg.minutes echo mailed mtg.minutes to $NAMES done

Cont.
for FILE in * do if test –d $FILE then ls –F $FILE

fi
done

The break, continue and exit commands
break [n]
terminates the iteration of the loop and skips to next command after [the nth] done

continue [n]
stops the current iteration of the loop and skips to the beginning of the next iteration [of the nth] enclosing loop

exit [n]
stops the execution of the shell program, and sets the return code to n

Examples:
while true do echo “Enter file to remove: \c” read FILE if test ! –f $FILE then echo $FILE is not a regular file continue fi echo removing $FILE rm $FILE break done