Here is an example of a while loop:
#!/bin/bash
count=1
while [ $count -le 9 ]
do
echo "$count"
sleep 1
(( count++ ))
done
#!/bin/bash
count=1
while [ $count -le 9 ]
do
echo "$count"
sleep 1
done
You can also create an infinite loop by putting a colon as the condition:
#!/bin/bash
count=1
while :
do
echo "$count"
sleep 1
(( count++ ))
done
count=1
done=0
while [[ $count -le 9 ] && [ $done == 0 ]]
do
echo "$count"
sleep 1
(( count++ ))
if [ $count == 5 ]; then $done=1
fi
done
The "&&" means logical "and" and "||" means logical "or".
An alternative notation for the conjunctions "and" and "or" in conditions is "-a" and "-o" with single square brackets. The above condition
[[ $count -le 9 ] && [ $done == 0 ]]
[ $count -le 9 ] -a [ $done == 0 ]
Reading a text file is typically done with a while loop. In the following example, the bash script reads the contends of a file "inventory.txt" line be line:
FILE=inventory.txt
exec 6<&0
exec 0<$FILE
while read line1
do
echo $line1
done
exec 0<&6
In the 3rd line the input file is assigned to file descriptor "0", which is used for standard input. The "read" statement then reads a line from the file on each iteration and assigns it to the variable "line1".
In order to prematurely exit a while-loop you can use the break statement as in the following example:
count=1
done=0
while [ $count -le 9 ]
do
echo "$count"
sleep 1
(( count++ ))
if [ $count == 5 ]
then
break
fi
done
echo Finished
The continue statement on the other hand skips only the rest of the while loop statement of the current iteration and jumps directly to the next iteration:
count=1
done=0
while [ $count -le 9 ]
do
sleep 1
(( count++ ))
if [ $count == 5 ]
then
continue
fi
echo "$count"
done
echo Finished
See also: the Bash for-loop.

