In the previous articles on Loop Statements, we have seen how a loop works. The For Loop as well as the While Loop keep executing a block of commands till the condition stays true. Once the condition becomes false, the loop is terminated.
Read More about 'FOR' and 'WHILE' Loops:
- Basic Linux Shell Scripting Language : Introduction to 'For' Loops
- Basic Linux Shell Scripting Language : 'While' Loops
In this article, we will see a different kind of loop that keeps executing a block of commands till the condition becomes true. The loop is known as 'Until' Loop and it works in totally opposite way as that of the 'While' Loop. Before we proceed to the tutorial part, I recommend that you should read my article on While loops and if you are new to Shell Scripting, please read- Getting Started - Linux Shell Scripting Language.
The 'Until' Loop
The until loop has a similar syntax as that of the while loop, but as quoted earlier, it works in totally opposite manner as that of while loop. Just like while loop, there is a block of commands and there is a condition. The block of commands executes repeatedly till the condition stays False. As soon as the condition becomes true, the 'until' loop terminates. Have a look on 'until' loop syntax:
until [ Condition ] do -- Block of Commands -- done
#!/bin/bash n=1 until [ $n -gt 5 ] do echo "This is Iteration No. $n" n=$( expr $n + 1 ) done
This is Iteration No. 1 This is Iteration No. 2 This is Iteration No. 3 This is Iteration No. 4 This is Iteration No. 5
An Infinite 'Until' LoopYou can create an Infinite 'until' loop by writing a condition which stays 'false' forever. Generally, most of the programmers prefer 'For' loops and 'While' loops to create an infinite loop.
until [ False_Condition ] do -- Block of Commands -- done
#!/bin/bash until [ 5 -ne 5 ] do echo "You are in an Infinite Loop. Press CTRL + C to Exit.." done
The 'Until' Loop with 'Continue' StatementThe continue statement in a loop, when certain condition becomes true, skips all the statements coming after it and continues with the next iteration of the loop.
Example: Again, lets print all the even numbers less than or equal to 20.
until [ condition ] do -- Some Commands -- if [ condition ] then continue fi -- More commands -- done
#!/bin/bash i=0 until [ $i -gt 20 ] do i=$(expr $i + 1) j=$(expr $i % 2) if [ $j -ne 0 ] then continue fi echo "$i" done
2 4 6 8 10 12 14 16 18 20
Script : Sum of Squares of First 'N' Natural Numbers
#!/bin/bash echo "Enter the Last Number" read n i=1 sum=0 until [ $i -gt $n ] do j=$(expr $i \* $i) sum=$(expr $sum + $j) i=$(expr $i + 1) done echo "Sum of Squares of First $n Natural Numbers = $sum"
Enter the Last Number 6 Sum of Squares of First 6 Natural Numbers = 91
That's all about Until Loops!