# While Loop and Until Loop

While loop; Until loop

Both for loops and while loops are very similar. Typically, we use for loops where we know exactly how many iterations we need – i.e. they have a definitive start and end point. On the other hand, while loops are used where we don’t know the limitations on tasks such as read in a file or asking a user for input. They just keep iterating as long as the specified condition has been met.

The basic syntax for a while loop looks like this:

while [condition]do # Commands to rundone

First, let’s look at how not to do a while loop:

i=1while [[ $i -eq 1 ]]do echo "hi"done This is what’s known as an infinite loop because the condition will always return true – i.e. nothing is changing. In this example, “hi” will just keep being printed to the terminal until we force it to stop using Ctrl+C on our keyboard. So, that was how to use while loops in the wrong way. But, what do they look like when they are being used properly: i=1while [[$i -le 3 ]]do echo "$i" (( i++ ))done What we’re doing here is setting our variable to have an initial value of 1. When the loop begins, our variable is 1 (i.e. less than 3) and so the condition returns true. That means that we’re going to execute the code body, returning our variable value, 1 to the terminal. Next, we increment our variable value from 1 to 2 using the ++ notation. This continues while our variable has a value less than or equal to 3. The result: 123 Another common use for while loops is reading in the contents of a file. Here is an example: while read datado echo "${data}"done < infile.txt

This is what is known as a while loop. What do we mean by this? In this example, the while loop will only keep iterating while there are lines to be read from the given input file. Here, infile.txt is the name of the file that we are going to be looping over. The read command will process the file, line by line, into the data variable. Once it reaches the end of the file, the while loop will be terminated.

## Until loop

We just looked at an example of a while loop. Now, we’re going to look at run-until loops. The main difference is that while loops are designed to run while a condition is satisfied and then terminate once that condition returns false. On the other hand, until loops are designed to run while the condition returns false and only terminate when the condition returns true.

The structure of until loops is almost identical to that of a while loop:

until [condition]do # Commands to rundone

For example, this loop would run until the variable is greater than 3:

i=1until [[ $i -gt 3 ]]do echo$i ((i++))done

This would output:

123