Loops for, while and until#

Most languages have a similar concept called a loop to repeat a certain task for all items in a list or while a certain expression is valid. Shell scripts are no exception and have a concept to iterate over a list of items or are expression based.

For Loops items in a list#

The for loop executes for every item in a list. This makes it ideal for processing data when the set of items is known.

Iterate over a list of numbers#
1#!/bin/bash
2for i in {1..10}
3do
4    echo "Number ... $i"
5done

This list can defined as a range or a list of items, but also a variable or a command output. In the example below the command seq is used to generate a list of numbers.

Iterate over a generated list of numbers#
1#!/bin/bash
2for i in `seq 1 10`
3do
4    echo "Number ... $i"
5done

Using a command output as input for a loop is commonly used to iterate over a list of items. If one of the files has space in the name, the command ls will return a list of files with spaces, but the loop will not be able to process the list correctly. The for loops over words and not items as other languages.

Iterate over a list of files insecurely#
1#!/bin/bash
2for i in `ls`
3do
4    echo $i
5done

Warning

The for loops over words and not items as other languages. Files and/or directories with spaces will be split into multiple items.

In the example below we iterate over the samen list of files in the current directory and print the name of each file. Only this time the for loop will be able to process the list correctly as all files are presented to the for loop as a word that can contain spaces.

Iterate over a list of files securely#
1#!/bin/bash
2for i in "$( ls )"
3do
4    echo "$i\n"
5done

For loops with an expression#

The for loop can also be used as a while loop and using a counter to iterate as in the example below. The counter is incremented each time the loop is executed.

Counter based for loop#
1#!/bin/bash
2for (( i=1; i<=10; i++ ))
3do
4    echo "Number ... $i"
5done

While loops#

The while loop executues a command as long as the control expression is true, and stops when it becomes false or when a break statement is executed.

While loop#
1#!/bin/bash
2COUNTER=0
3while [  $COUNTER -lt 10 ]; do
4    echo The counter is $COUNTER
5    let COUNTER=COUNTER+1
6done

Until loops#

The until loop is similar to the while loop, but the condition is inverted. Meaning that the loop will execute as long as the condition is false.

Until loop#
1#!/bin/bash
2COUNTER=20
3until [  $COUNTER -lt 10 ]; do
4    echo COUNTER $COUNTER
5    let COUNTER-=1
6done