Script Valley
Bash Scripting for Developers
Control Flow and LogicLesson 2.2

Bash for loops and while loops with examples

C-style for loop, for-in loop, while loop, until loop, break and continue, loop over files, loop over command output, IFS variable

Looping in Bash

Bash loop iteration model

Bash has multiple loop types. Choose based on what you're iterating: a list, a range, or a condition.

# For-in: iterate a list
for fruit in apple banana cherry; do
  echo "Processing: $fruit"
done

# C-style: numeric range
for (( i=1; i<=5; i++ )); do
  echo "Step $i"
done

# Brace expansion shortcut
for i in {1..10}; do
  echo $i
done

While Loop

count=0
while [[ $count -lt 5 ]]; do
  echo "Count: $count"
  (( count++ ))
done

# Read file line by line โ€” the correct way
while IFS= read -r line; do
  echo "Line: $line"
done < /etc/hosts

Looping Over Files

# Glob expansion โ€” handles spaces in filenames correctly
for file in /var/log/*.log; do
  [[ -f "$file" ]] || continue
  echo "Processing: $file"
done

# Loop over command output โ€” avoid this pattern:
# for f in $(ls); do  โ† breaks on spaces
# Use glob instead

IFS= read -r line is the canonical way to read files. IFS= prevents leading/trailing whitespace stripping. -r prevents backslash interpretation. Skipping either causes subtle data corruption.

Up next

Bash case statement for multi-branch logic

Sign in to track progress

Bash for loops and while loops with examples โ€” Control Flow and Logic โ€” Bash Scripting for Developers โ€” Script Valley โ€” Script Valley