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 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
doneWhile 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/hostsLooping 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 insteadIFS= 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.
