For Loops in Bash
Using a for
loop in Bash is simple!
for loop over strings
1for i in "follow" "the" "white" "rabbit"; do
2 echo "${i}"
3done
1follow
2the
3white
4rabbit
for loop with range
1for i in {0..2}; do
2 echo "${i}"
3done
10
21
32
bash
4 added an increment parameter for ranges
1for i in {0..6..2}; do
2 echo "${i}"
3done
10
22
34
46
for loop with array
1a=("fried" "green" "tomatoes")
2for i in ${a[@]}; do
3 echo "${i}"
4done
1fried
2green
3tomatoes
for loop C-style
1for (( i = 0; i <= 3; i++ )); do
2 echo "${i}"
3done
10
21
32
43
for loop control statements: break & continue
break statement
The break
statement terminates the current loop.
1for i in "first" "second" "break" "third"; do
2 if [[ "${i}" == "break" ]]; then
3 break
4 fi
5 echo "${i}"
6done
1first
2second
continue statement
The continue
statement skips the current iteration and ‘continues’ to the next iteration.
1for i in "first" "second" "break" "third"; do
2 if [[ "${i}" == "break" ]]; then
3 continue
4 fi
5 echo "${i}"
6done
1first
2second
3third