Bash Script Loops

A loop statement allows the execution of a statement or group of statements multiple times. There are three main types of loop statement in Bash Script.

  • ‘for’ loop – Useful when it is known in advance the number of times the statements within the loop need to be executed.
  • ‘while’ loop – Repeats a statement or group of statements while an expression evaluates to true. There is a condition to get into the loop, so if the condition evaluates to true at the beginning then the statements inside the loop will never execute.
  • ‘until’ loop – This is similar to the ‘while’ loop except that the statements within are executed until the expression evaluates to true.

‘for’ Loop

A 'for' loop in Bash Script can work on a range, or a list of values, and takes the following form.

for value in range/list
do
    # Statement(s) to execute.
done

The following example specifies a range of one to five, and displays the value of 'I', which is the current value of the range, each time through the loop.

#!/bin/bash

for I in {1..5}
do
    echo "$I"
done

The resulting output is shown below.

1
2
3
4
5

A 'for' loop can also work on a list of values. Here, the 'for' loop is used to print out the names contained in the list.

#!/bin/bash

PNAMES="Bob George Fred Alan"

for I in $PNAMES
do
    echo "$I"
done

This displays the list of names as follows.

Bob
George
Fred
Alan

‘while’ Loop

As mentioned above, the ‘while’ loop has a condition, which must evaluate to true before the statements within it can be executed.

while [ condition ]
do
    # Statement(s) to execute.
done

In the below example, a variable is declared and initialised to one, then the ‘while’ loop checks to see that the variable is less than or equal to five before outputting it to the screen and incrementing the variable by one.

#!/bin/bash

I=1

while [ $I -le 5 ]
do
    echo "$I"
    ((I++))
done

The output will be the same as in the ‘for’ loop example above. Note that if the variable ‘I’ had been declared and initialised to six or above, then the statements within the loop would not be executed at all.

‘until’ Loop

The 'until' loop looks similar to the 'while' loop, with just the substitution of the word 'while' with 'until'. This time the loop operates until the condition is true.

until [ condition ]
do
    # Statement(s) to execute.
done

Here, a variable, 'I', is set to one and the statements within the loop execute until the variable is greater than five. Within the loop, the value of the variable is displayed to the screen and then incremented by one. Again, the output is the same as the 'for' loop above.

#!/bin/bash

I=1

until [ $I -gt 5 ]
do
    echo "$I"
    ((I++))
done

Note that if the variable ‘I’ had been declared and initialised to six or above, then the statements within the loop would not be executed at all.