Bash Loops

Bash provides for loops to iterate over lists and while loops to repeat while a condition holds true.

The for Loop

A for loop iterates over a list of words, filenames, or a numeric range, running its body once per item. The current item is bound to a loop variable you name after for, and the list to iterate over follows the in keyword.

Example

#!/bin/bash
for color in red green blue; do
  echo "Color: $color"
done

for i in {1..5}; do
  echo "Count: $i"
done

C-Style for Loops

Bash also supports a C-style for loop with an initializer, a condition, and an increment expression, all separated by semicolons and wrapped in double parentheses. This style is useful when you need explicit control over the counter, such as stepping by more than one.

Example

#!/bin/bash
for ((i = 0; i < 10; i += 2)); do
  echo "Even number: $i"
done

The while Loop

A while loop repeats its body as long as its condition remains true, checking the condition before every iteration. It is the natural choice when the number of iterations isn't known in advance, such as reading lines from a file or waiting for a state to change.

  • for loop -- best when iterating a known list, array, or range
  • while loop -- best when repeating until a condition changes
  • until loop -- like while, but repeats until the condition becomes true
  • break exits the loop immediately; continue skips to the next iteration

Example

#!/bin/bash
count=1

while [ "$count" -le 5 ]; do
  echo "Attempt $count"
  count=$((count + 1))
done
Note: Use while read -r line; do ... done < file.txt to process a file line by line -- the -r flag prevents backslashes in the file from being interpreted.
Note: Forgetting to update the loop variable inside a while loop (like count=$((count + 1))) causes an infinite loop, since the condition never changes.

Exercise: Bash Loops

What does `for item in list; do ... done` iterate over?