Using loops in Bash

Date: February 23rd, 2011
Author: Mark Kolin

In Bash you have three constructs for loops – for, while and until.
The while construct basically executes a piece of code while a given expression (called control expression) evaluates to true. The while loop stops when the control expression evaluates to false (or a break is executed)

The for construct is a little different from what we have seen in other languages. It can be thought that it iterates the words in a string.

The until loop resembles the while loop. The difference is that the code in the loop is executed until the control expression evaluates to true (while it evaluates to false). Naturally the until construct resembles the while construct.

Let’s start with an example of the while construct:

  1. count=0
  2. while [ $count -lt 5 ]; do
  3.  echo Our counter is $count
  4.  let count=count+1
  5. done

Basically the loop executes while count is less than 5. The body of the loop is between do and done. Note that the control expression must be in “[]” (there are alternatives, but this will do fine). Also note that do is either on a new line or is preceded by “;” (and that goes for the for-loop and until-loop as well). And that is pretty much all there is about the while loop.

The [b]until[/b] loop is pretty much the same:
until [ $count -lt 1 ]; do
echo Our counter is $count
let count=count-1
All that is left is the [b]for[/b] construct, so let

VN:F [1.9.18_1163]
Rating: 0.0/10 (0 votes cast)

Leave a Reply