Loops

Loops are used for automating repetitive tasks and continue to run until a specific condition is met.

 

The main loop structures in shell scripting are:

 

  • for
  • while

 

Syntax of a for loop:

 

for value in source
do

command

done

 

*where source can be:

  • a number of separately listed items
  • a variable
  • an array
  • a substituted command e.g. $(command)
#!/bin/bash

for value in 1 2 3
do
	echo "Loop iteration: $value"
done

for value in cat dog bird
do
	echo "$value"
done

bikes="Ducati Aprilia Triumph Yamaha Suzuki Honda"
for value in $bikes
do
	echo $value
done

array=(The cat sat on the mat)
for value in ${array[*]}
do
	echo $value
done

echo $bikes > bikes.txt
for value in $(cat bikes.txt)
do
	echo $value
done

#using a range
for i in {2..7}
do
	echo $(( $i * 6 ))
done

#as above with step value
for i in {2..17..3}
do
	echo $(( $i * 6 ))
done

 

 

Syntax of a while loop:

 

while condition
do

command

done

 

Basically, while the condition is true, do the following command.

 

#!/bin/bash

i=0
while [ $i -lt 10 ]
do
	echo $i
	((i++))
done

 

Another example, this time using a colon : to indicate an infinite loop. TRUE could also have been used instead of the :

#!/bin/bash

echo "press Ctrl C, to quit"
while :
do
	clear
	echo $i
	((i++))
done