The until Statement

The until statement can be used to execute a series of commands until a specified condition is true.

The loop terminates as soon as the specified condition evaluates to TRue.

In pdksh and bash, the following format is used:

until expression do statements done

As you can see, the format of the until statement is similar to that of the while statement, but the logic is different: In a while loop, you execute until an expression is False, but in an until loop, you loop until the expression is TRue.

If you want to add the first five even numbers, you can use the following shell program in pdksh and bash:

#!/bin/bash loopcount=0 result=0

until [ $loopcount -ge 5 ] do loopcount=Nexpr $loopcount + iN increment=Nexpr $loopcount \* 2N result=Nexpr $result + $incrementN done echo "result is $result"

The example here is identical to the example for the while statement, except that the condition being tested is just the opposite of the condition specified in the while statement.

The tcsh shell does not support the until statement.

The repeat Statement (tcsh)

The repeat statement is used to execute only one command a fixed number of times.

If you want to print a hyphen (-) 80 times with one hyphen per line on the screen, you can use the following command:

The select Statement (pdksh)

The select statement is used to generate a menu list if you are writing a shell program that expects input from the user online. The format of the select statement is as follows:

select item in itemlist do

Statements done itemlist is optional. If it isn't provided, the system iterates through the item entries one at a time. If itemlist is provided, however, the system iterates for each entry in itemlist and the current value of itemlist is assigned to item for each iteration, which then can be used as part of the statements being executed.

If you want to write a menu that gives the user a choice of picking a Continue or a Finish, you can write the following shell program:

#!/bin/ksh select item in Continue Finish do if [ $item = "Finish" ]; then break fi done

When the select command is executed, the system displays a menu with numeric choices to the userin this case, 1 for Continue and 2 for Finish. If the user chooses 1, the variable item contains a value of Continue; if the user chooses 2, the variable item contains a value of Finish. When the user chooses 2, the if statement is executed and the loop terminates.

0 0

Post a comment