For Loops in Bash

Using a for loop in Bash is simple!

for loop over strings

1
2
3
for i in "follow" "the" "white" "rabbit"; do
    echo "${i}"
done
1
2
3
4
follow
the
white
rabbit

for loop with range

1
2
3
for i in {0..2}; do
    echo "${i}"
done
1
2
3
0
1
2

bash 4 added an increment parameter for ranges

1
2
3
for i in {0..6..2}; do
    echo "${i}"
done
1
2
3
4
0
2
4
6

for loop with array

1
2
3
4
a=("fried" "green" "tomatoes")
for i in ${a[@]}; do
    echo "${i}"
done
1
2
3
fried
green
tomatoes

for loop C-style

1
2
3
for (( i = 0; i <= 3; i++ )); do
    echo "${i}"
done
1
2
3
4
0
1
2
3

for loop control statements: break & continue

break statement

The break statement terminates the current loop.

1
2
3
4
5
6
for i in "first" "second" "break" "third"; do
    if [[ "${i}" == "break" ]]; then
        break
    fi
    echo "${i}"
done
1
2
first
second

continue statement

The continue statement skips the current iteration and ‘continues’ to the next iteration.

1
2
3
4
5
6
for i in "first" "second" "break" "third"; do
    if [[ "${i}" == "break" ]]; then
        continue
    fi
    echo "${i}"
done
1
2
3
first
second
third