Basic Linux Tutorial
Computer Tutorial

The for-do-done Loop



The for-do-done Loop

The for-do-done loop is executed on a list of elements. The list of elements is assigned to a variable one-by-one. The value of this variable is processed inside the loop. The loop continues to execute until all of the list elements are processed and there are no more elements in the list.

The general syntax of for-do-done loop :


for   var in list
do
command block
done

The construct works as follows

1. The shell variable var is set equal to the first string in list.
2. Command command block is executed.
3. The shell variable var is set equal to the next string in list.
4. Command command block is executed.
5. Continue until all items from list have been processed.

Flow chart of do-done-for Loop

for do done Loop

Example of do-done-for Loop

#!/usr/bin/sh
for   X   in   1   2   3   4   5
do

echo  "2 * $X is \c"
let X = X * 2
echo  $X



done