Beruflich Dokumente
Kultur Dokumente
Three Forms
while ... do ... done until ... do ... done for ... do ... done
$ 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
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 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
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
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