Shell For Loops
For Loops
The while loop enables you to execute a set of commands repeatedly until some condition occurs. It is usually used when you need to manipulate the value of a variable repeatedly.
Syntax
for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
done
Example
#!/bin/sh
for var in 0 1 2 3 4 5 6 7 8 9
do
echo $var
done
#!/bin/bash
for table in {2}
do
echo "table for 2: $table"
done
#!/bin/bash
for table in {2,3,4,5,6}
do
echo "table for 2: $table"
done
#!/bin/bash
for table in {2..20}
do
echo "table for 2: $table"
done
#!/bin/bash
for ((i=0; i<5; i++ ))
do
echo "the value is $i"
done
The list of values (Mon, Tue, Wed, Thu and Fri) are directly given after the keyword “in” in the bash for loop.
#!/bin/bash
i=1
for day in Mon Tue Wed Thu Fri
do
echo "Weekday $((i++)) : $day"
done
#!/bin/bash
i=1
for day
do
echo "Weekday $((i++)) : $day"
done
$ ./forweek1.sh Mon Tue Wed Thu Fri