Bash while loop
Page content
Source
https://linuxize.com/post/bash-while-loop/
while loop
while [CONDITION]
do
[COMMANDS]
done
Example
i=0
while [ $i -le 2 ]
do
echo Number: $i
((i++))
done
Infinite while Loop
while :
do
echo "Press <CTRL+C> to exit."
sleep 1
done
Single line
while :; do echo 'Press <CTRL+C> to exit.'; sleep 1; done
Read a File Line by Line
file=/etc/passwd
while read -r line; do
echo $line
done < "$file"
Break Statement
i=0
while [ $i -lt 5 ]
do
echo "Number: $i"
((i++))
if [[ "$i" == '2' ]]; then
break
fi
done
echo 'All Done!'
Output
Number: 0
Number: 1
All Done!
continue Statement
i=0
while [ $i -lt 5 ]
do
((i++))
if [[ "$i" == '2' ]]; then
continue
fi
echo "Number: $i"
done
echo 'All Done!'
Output
Number: 1
Number: 3
Number: 4
Number: 5
All Done!
sha256: 6c727d48f8c136dac021ca193c7b1b46b6ad41a4e6a37344251d08d85485666b