5.3 While Loops
The while loop
while executes code while the control expression is true and until it is false.
The while loop
COUNTER=0
while [ $COUNTER -lt 3 ]; do
echo "The counter is $COUNTER"
let COUNTER=COUNTER+1
done
#The counter is 0
#The counter is 1
#The counter is 2
We can also use a while loop to read over all lines of a file. For that we need to use “while read” follow by a variable name and use the operator “<” to redirect the STDIN to a file. Keep in mind, in this case a counter is not needed since the looping while be over once we reach the end of the file.
while read line; do
echo "Line: $line"
done < ls.txt
#Line: ls.all
#Line: ls.errl
#Line: ls.txt
#Line: out.txt
The variable line contains every time a new line from ls.txt (input is redirected with <)