Back to Blog

Zsh Shell Tutorial 10: Loops — for, while, until & File Processing

Sandy LaneSandy Lane

Video: Zsh Shell Tutorial 10: Loops — for, while, until & File Processing by Taught by Celeste AI - AI Coding Coach

Watch full page →

Zsh Shell Tutorial 10: Loops — for, while, until & File Processing

This tutorial covers all the essential looping constructs in Zsh scripting, including for loops with various syntaxes, while and until loops for conditional repetition, and flow control using break and continue. It also demonstrates how to process files efficiently using glob patterns and while-read loops for line-by-line reading.

Code

# For loop iterating over a list of items
for item in apple banana cherry; do
  echo "Fruit: $item"
done

# For loop using brace expansion (numbers 1 to 5)
for i in {1..5}; do
  echo "Number: $i"
done

# C-style for loop (initialization; condition; increment)
for ((i=0; i<3; i++)); do
  echo "C-style loop iteration $i"
done

# While loop: repeat while condition is true
count=1
while (( count <= 3 )); do
  echo "While loop count: $count"
  ((count++))
done

# Until loop: repeat until condition becomes true
count=1
until (( count > 3 )); do
  echo "Until loop count: $count"
  ((count++))
done

# Break and continue in loops
for i in {1..5}; do
  if (( i == 3 )); then
    echo "Skipping 3"
    continue   # Skip iteration when i is 3
  fi
  if (( i == 5 )); then
    echo "Breaking at 5"
    break      # Exit loop when i is 5
  fi
  echo "Value: $i"
done

# File processing using glob pattern and while-read loop
for file in *.txt; do
  echo "Processing file: $file"
  while IFS= read -r line; do
    echo "Line: $line"
  done < "$file"
done

Key Points

  • For loops in Zsh can iterate over lists, brace expansions, or use C-style syntax for flexible iteration.
  • While loops run as long as a condition is true, whereas until loops run until a condition becomes true.
  • Break exits a loop immediately, and continue skips the current iteration to proceed to the next.
  • Glob patterns enable easy file selection for batch processing in loops.
  • Using while-read loops allows safe, line-by-line reading of file contents within scripts.