Shell
shellshell-scriptingGuideBeginner
Bash Loops: for, while, and Reading Files
Iterate over lists, files, and numbers using for and while loops, and process text line-by-line in Bash.
Verified: 2026-09-30
Tested on:bash 5.x
Platforms:
linuxmacos
#shell#bash#loops#for-loop#while-loop
1. for Loop Over a List
#!/usr/bin/env bash
SERVERS=("web-1" "web-2" "db-1" "cache-1")
for SERVER in "${SERVERS[@]}"; do
echo "Pinging $SERVER..."
# ssh "$SERVER" "uptime"
done2. Iterating Over Files (Globbing)
# Process all markdown files in directory
for FILE in content/docs/*.md; do
# Verify path is actually a file (handles empty directories safely)
[[ -f "$FILE" ]] || continue
echo "Validating $FILE..."
done3. C-Style Number Ranges
# Loop from 1 to 5
for ((i = 1; i <= 5; i++)); do
echo "Attempt #$i"
done
# Brace expansion shorthand
for i in {1..5}; do
echo "Step $i"
done4. while Loop & Reading Files Line-by-Line
To safely process a file line-by-line without word-splitting issues:
#!/usr/bin/env bash
INPUT_FILE="urls.txt"
# IFS= prevents trimming leading/trailing whitespace; -r prevents backslash escape interpretation
while IFS= read -r LINE || [[ -n "$LINE" ]]; do
# Skip comments and empty lines
[[ "$LINE" =~ ^#.*$ || -z "$LINE" ]] && continue
echo "Fetching status for: $LINE"
curl -Is "$LINE" | head -n 1
done < "$INPUT_FILE"5. Infinite Polling Loop with Sleep
echo "Waiting for database container to become healthy..."
while ! docker exec postgres-dev pg_isready -q; do
sleep 1
done
echo "Database is ready!"Bash Conditions & Comparison Operators
Master if/elif/else statements, test conditions ([[ ... ]]), string/numeric operators, file tests (-f, -d), and case statements.
Bash Functions & Scope
Define modular Bash functions, handle positional arguments ($1, $2, $@), manage local variable scope, and handle return values.