for-loop
Most of you probably know how a for-loop is supposed to work. We want to be able to repeat a certain code n number of times, or loop through the contents of a data structure.
for…in
#!/usr/bin/env bash
#
# An example script on for...in
# for...in range
for value in 1 2 3 4 5
do
echo "$value"
done
# for...in range, ({START..END})
for value in {1..5}
do
echo "$value"
done
# for...in range with steps, ({START..END..INCREMENT})
for value in {1..10..2}
do
echo "$value"
done
An alternative is to use arithmetic expansion, (( ))
. It gives the opportunity to write a more C-like construction. Note that it also works for the conditions in the if statement.
#!/usr/bin/env bash
#
# An example script on traditional for-loop
for (( i=0; i<10; i++ ))
do
if (( "$i" % 2 == 0 ))
then
echo "$i is even"
else
echo "$i is odd"
fi
done
#Revision history
- 2019-08-19: (A, lew) First edition.