View and vote on the article here: Shell Programming Series(VIII)
Shell Programming Series(VIII)| Category | | | Summary | The <TT>until</TT> Loop
The <TT>until</TT> loop is the opposite of the <TT>while</TT> loop. It performs the operations inside the loop as long as the condition being tested is not true. When the condition being |
| | Body | The <TT>while</TT> loop and the <TT>until</TT> loop are very similar. Usually, you can use either one in a program and achieve the same results simply by modifying the condition that is tested for. For example, the counting program [previous program] that used the <TT>while</TT> loop can be rewritten to use an <TT>until</TT> loop by making only two changes in line 4:
4. while [ $i -ge 20 ]
The program performs the exact same function. The only difference is that now the loop repeats until the value of i is greater than 20, whereas before it repeated while the value of i was less than or equal to 20. The result is exactly the same, however.
Logical AND/OR Statements in <TT>while</TT> and <TT>until</TT> Loops
Both the <TT>while</TT> and the <TT>until</TT> loop can also work with logical AND/OR statements. A logical AND statement will be carried out if and only if both conditions are true. A logical OR statement will be carried out if either condition is true. The following code sample shows a logical AND statement:
#!/bin/sh
# Demonstrate logical AND
Var1=2
Var2=6
while [ $Var1 -eq 2 ] && [ $Var2 ?gt 8 ]
do
echo ? Var1 is equal to 2 and Var2 is greater than 8?
done
exit 0
In the previous example, the echo statement will not be executed because although $Var1 is equal to 2, $Var2 is not greater than 8. And since the while loop in this case requires both conditions to be true, the test fails and returns a 0 (false).
The following code sample is identical to the previous one, except we have changed the <TT>while</TT> test to a logical OR statement. Now, only one of the conditions needs to be true:
#!/bin/sh
# Demonstrate logical OR
Var1=2
Var2=6
while [ $Var1 -eq 2 ] || [ $Var2 ?gt 8 ]
do
echo ? Var1 is equal to 2 or Var2 is greater than 8?
done
exit 0
In this case, only one condition needs to be true. And since $Var1 will always be equal to 2 in this program, the result will be an infinite loop that prints the echo statement over and over again endlessly. (To break out of this loop, press Ctrl ? C on your keyboard.)
|
|
This article was imported from zZine. (original author: ismail)
There are no replies to this post yet.
|