For loops are the most commonly used loops in Bash for iterating over a series of values.
for item in list
do
echo "$item"
done
for ((i=0; i<10; i++))
do
echo "$i"
done
for i in $(seq 1 5)
do
echo "$i"
done
{1..5}
for ranges, but seq
is more compatible across versions (including v3).
for i in $(seq 1 5); do echo "$i"; done
While loops continue executing as long as a condition is true.
count=1
while [ $count -le 5 ]
do
echo "$count"
count=$((count + 1))
done
Looping through arrays is a common task in Bash scripting.
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"
do
echo "$fruit"
done
for file in *
do
echo "Processing $file"
done
"$file"
while true
do
echo "This will run forever"
sleep 1
done
Until loops continue executing until a condition becomes true.
count=1
until [ $count -gt 5 ]
do
echo "$count"
count=$((count + 1))
done
for i in $(seq 1 10)
do
if [ $i -eq 5 ]
then
break
fi
echo "$i"
done
for i in $(seq 1 5)
do
if [ $i -eq 3 ]
then
continue
fi
echo "$i"
done