For loops in bash a similar to commonly used languages such as Perl and C. bash loops do not use curly brackets for body demarcation.

Example 1

clear
for i in 1 2 3 4 5 6 7 8 9
do
   echo "printing number $i"
done

Loop start from the do statement and ends with the done statement. This code prints numbers as follows:

printing number 1
printing number 2
printing number 3
printing number 4
printing number 5
printing number 6
printing number 7
printing number 8
printing number 9

Example 2

j=1;
for i in 1 2 3 4 5 6 7 8 9
do
   j=$j*$i
   echo $j
done

You would expect this code to multiply numbers and print their results but this code concatenated the values instead. bash treats all variables as strings and there is no casting. The output of the program is as follows:

1*1
1*1*2
1*1*2*3
1*1*2*3*4
1*1*2*3*4*5
1*1*2*3*4*5*6
1*1*2*3*4*5*6*7
1*1*2*3*4*5*6*7*8
1*1*2*3*4*5*6*7*8*9

Example 3

j=1;
for i in 1 2 3 4 5 6 7 8 9
do
   j=`echo "$j * $i" | bc`
   echo $j
done

This code actually does what we expected the previous one to do. It multiplies variables and prints the results. We used echo to write the mathematical equation e.g. 2 * 3, and then pipe the string to bc. bc is a commandline calculator and it returned the value 6 which was stored in the variable j as a string and then printed to the screen with the following line of code.

1
2
6
24
120
720
5040
40320
362880

By master