Tuesday, January 16, 2007

While Vs Until


A very very important academic question, difference between while loop and until loop

* While: executes the body of the loop so long as the conditional expression is true
* Until: executes the body of the loop so long as the conditional expression is false

Two simple scripts to illustrate the use of both:

$ cat while.sh
#!/bin/sh

count=1
while [ "$*" != "" ]

do
echo "Argument number $count): $1"
shift
count=`expr $count + 1`
done

$ cat until.sh
#!/bin/sh

count=1
until [ "$*" = "" ]
do
echo "Argument number $count): $1"
shift
count=`expr $count + 1`
done

$ ./while.sh one 2 Three 4
Argument number 1): one
Argument number 2): 2
Argument number 3): Three
Argument number 4): 4

* Similar output for until.sh

No comments:

© Jadu Saikia www.UNIXCL.com