Script Valley
Linux & Bash for Developers
Bash Scripting FundamentalsLesson 3.4

Bash loops: for while and until explained

for loop syntax, C-style for loop, while loop, until loop, loop control break continue, looping over files, seq command, loop over array

Loops Automate Repetition

Bash has three loop types. for iterates over a list. while runs while a condition is true. until runs until a condition becomes true. In practice, for covers most scripting needs.

for Loop Patterns

#!/bin/bash

# Loop over a list of values
for ENV in dev staging production; do
  echo "Deploying to: $ENV"
done

# Loop over files in a directory
for FILE in /var/log/*.log; do
  echo "Processing: $FILE"
  wc -l "$FILE"
done

# C-style for loop
for ((i=1; i<=5; i++)); do
  echo "Iteration $i"
done

# Using seq
for i in $(seq 1 10); do
  echo "Item $i"
done

while and Loop Control

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

# Read a file line by line
while IFS= read -r LINE; do
  echo "Line: $LINE"
done < /etc/hosts

# break exits the loop early
# continue skips to the next iteration
for i in 1 2 3 4 5; do
  [[ $i -eq 3 ]] && continue
  [[ $i -eq 5 ]] && break
  echo $i
done
# Output: 1 2 4

Reading a file with while IFS= read -r LINE is the correct pattern โ€” it preserves leading/trailing whitespace and handles lines without a trailing newline.

Up next

Bash functions: how to write reusable code

Sign in to track progress

Bash loops: for while and until explained โ€” Bash Scripting Fundamentals โ€” Linux & Bash for Developers โ€” Script Valley โ€” Script Valley