BASH Loops
Bash supports both while
and for
loop. Each has some variants to help us do our work better!
Control statements
Besides loop condition, both while
and for
loop, undesrtands common control commands:
break
- finish loop execution immediatelycontinue
- jump to next iteration now
While loop
While loop with condition
foo=1
while [ $x -le 10 ]
do
echo "Iteration ${foo}"
foo=$(( $foo + 1 ))
done
Dead while loop
Loop without condition is a dead loop
while :
do
echo "I' the DEAD LOOP!"
done
echo "Unreachable code"
Unless there is a break in it
while :
do
break
echo "Unreachable code"
done
echo "I'm free!"
For loop
With explicit list of items
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "Iteration ${i}"
done
For loop with range
for i in {1..10}
do
echo "Iteration ${i}"
done
every third element
for i in {1..10..3}
do
echo "Iteration ${i}"
done
C style! 💃
for (( i=1; i<=10; i++ ))
do
echo "Iteration ${i}"
done
Dead loop again!
for (( ; ; ))
do
echo "I' the DEAD LOOP!"
done
echo "Unreachable code"
But we can use break
just like in while
loop