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}"
3done1follow
2the
3white
4rabbitfor loop with range
1for i in {0..2}; do
2 echo "${i}"
3done10
21
32
bash4 added an increment parameter for ranges
1for i in {0..6..2}; do
2 echo "${i}"
3done10
22
34
46for loop with array
1a=("fried" "green" "tomatoes")
2for i in ${a[@]}; do
3 echo "${i}"
4done1fried
2green
3tomatoesfor loop C-style
1for (( i = 0; i <= 3; i++ )); do
2 echo "${i}"
3done10
21
32
43for 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}"
6done1first
2secondcontinue 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}"
6done1first
2second
3third