Skip to content

Loops

Loops allow you to execute the same code on different values of a variable Below, we give the syntax and examples for for and while loops.

for loops

General syntax:

1
2
3
4
for var in list
do
   Statement(s) to be executed using $var
done

Here, var is a variable name, and list is a list of items separated by white space that var will take on in the loop iterations.

Example:

test.sh
1
2
3
4
5
#!/bin/sh
for i in 1 2 3 4 5
do
  echo "Looping ... number $i"
done

This is the result of a sample run.

1
2
3
4
5
6
$ sh test.sh
Looping ... number 1
Looping ... number 2
Looping ... number 3
Looping ... number 4
Looping ... number 5

The looping expression can also use a format similar to a C for loop. For example, this script also gives a same results.

1
2
3
4
5
#!/bin/sh
for ((i=1 ; i<6; i++))
do
  echo "Looping ... number $i"
done

while loops

General syntax:

1
2
3
4
while [ expression ]
do
   Statement(s) to be executed
done

Here, expression is a conditional expression as described in Conditional statements.

Example:

test.sh
1
2
3
4
5
6
7
8
#!/bin/sh
INPUT_STRING=hello
while [ "$INPUT_STRING" != "bye" ]
do
  echo "Please type something in (bye to quit)"
  read INPUT_STRING
  echo "You typed: $INPUT_STRING"
done

This is the result of a sample run.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$sh test.sh
Please type something in (bye to quit)
hello
You typed: hello
Please type something in (bye to quit)
hi
You typed: hi
Please type something in (bye to quit)
bye
You typed: bye
$