While Loops
While loops execute commands repeatedly as long as a condition is true. They're perfect when you don't know in advance how many iterations you'll need.
Basic While Syntax
while [ condition ]; do
commands
done
The loop continues as long as the condition evaluates to true (exit status 0).
Simple Counter Example
#!/bin/bash
COUNT=1
while [ $COUNT -le 5 ]; do
echo "Count: $COUNT"
COUNT=$((COUNT + 1))
done
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
While with Arithmetic
Using (( )) for cleaner syntax:
#!/bin/bash
i=0
while (( i < 5 )); do
echo "i = $i"
(( i++ ))
done
Exercise: While Loop Counter
Create a simple while loop:
Reading Files Line by Line
The most common use of while loops:
#!/bin/bash
while read -r line; do
echo "Line: $line"
done < input.txt
Processing CSV Data
#!/bin/bash
while IFS=',' read -r name age city; do
echo "Name: $name, Age: $age, City: $city"
done < data.csv
Reading from Command Output
Process command output line by line:
#!/bin/bash
# Using process substitution
while read -r file; do
echo "Processing: $file"
done < <(find . -name "*.txt")
# Using pipe (runs in subshell!)
find . -name "*.txt" | while read -r file; do
echo "Processing: $file"
done
Important: With pipes, the while loop runs in a subshell, so variables set inside won't persist.
Exercise: Read from Pipe
Read lines from a command:
Infinite While Loops
Loop forever until explicitly broken:
#!/bin/bash
while true; do
echo "Running..."
sleep 1
# Break condition
if [ -f "stop.flag" ]; then
echo "Stop flag detected"
break
fi
done
Or using : (always true):
while :; do
echo "Still running..."
sleep 1
done
While with Multiple Conditions
Combine conditions with logical operators:
#!/bin/bash
count=0
max=10
found=false
while [ $count -lt $max ] && [ "$found" = "false" ]; do
count=$((count + 1))
echo "Checking $count..."
if [ $count -eq 5 ]; then
found=true
fi
done
Menu Loop Pattern
Interactive menus:
#!/bin/bash
while true; do
echo "1) Option One"
echo "2) Option Two"
echo "3) Exit"
read -p "Choose: " choice
case $choice in
1) echo "You chose One" ;;
2) echo "You chose Two" ;;
3) echo "Goodbye!"; break ;;
*) echo "Invalid option" ;;
esac
done
While with Read and Timeout
Add timeout to prevent hanging:
#!/bin/bash
while read -t 5 -r input; do
echo "You entered: $input"
done
echo "Timed out or EOF"
Retry Loop Pattern
Retry operations with backoff:
#!/bin/bash
MAX_RETRIES=5
RETRY=0
while [ $RETRY -lt $MAX_RETRIES ]; do
if some_command; then
echo "Success!"
break
else
RETRY=$((RETRY + 1))
echo "Attempt $RETRY failed, retrying..."
sleep $((RETRY * 2)) # Exponential backoff
fi
done
if [ $RETRY -eq $MAX_RETRIES ]; then
echo "All retries failed"
exit 1
fi
Monitoring Loop
Watch for changes:
#!/bin/bash
LAST_SIZE=0
while true; do
CURRENT_SIZE=$(wc -c < logfile.txt)
if [ "$CURRENT_SIZE" -gt "$LAST_SIZE" ]; then
echo "File grew: $LAST_SIZE -> $CURRENT_SIZE bytes"
LAST_SIZE=$CURRENT_SIZE
fi
sleep 5
done
Nested While Loops
Loops within loops:
#!/bin/bash
outer=1
while [ $outer -le 3 ]; do
inner=1
while [ $inner -le 3 ]; do
echo "outer=$outer, inner=$inner"
inner=$((inner + 1))
done
outer=$((outer + 1))
done
Reading Multiple Values
Parse structured input:
#!/bin/bash
# Data format: name:score
while IFS=':' read -r name score; do
echo "$name scored $score"
done << EOF
Alice:95
Bob:87
Carol:92
EOF
Exercise: Until Condition Met
Loop until a condition changes:
Common Pitfalls
Variable Not Updating
# WRONG - runs forever!
COUNT=1
while [ $COUNT -le 5 ]; do
echo $COUNT
# Forgot to increment!
done
# CORRECT
COUNT=1
while [ $COUNT -le 5 ]; do
echo $COUNT
COUNT=$((COUNT + 1))
done
Pipeline Subshell Issue
# WRONG - variable doesn't persist
count=0
cat file.txt | while read -r line; do
count=$((count + 1))
done
echo "Lines: $count" # Always 0!
# CORRECT - use process substitution
count=0
while read -r line; do
count=$((count + 1))
done < <(cat file.txt)
echo "Lines: $count" # Correct count
Best Practices
- Always have an exit condition: Prevent infinite loops
- Use
read -r: Prevents backslash interpretation - Quote variables: Handle spaces in data
- Avoid pipe + while: Variables won't persist
- Consider alternatives:
formight be cleaner for fixed iterations
Key Takeaways
while [ condition ]; do ... doneloops while condition is true- Use
while read -r lineto process files line by line while truecreates infinite loops (usebreakto exit)- Variables in piped while loops don't persist - use process substitution
- Use
(( ))for cleaner arithmetic conditions - Always ensure your loop has a working exit condition
read -rprevents backslash interpretation

