Bash Tutorial · Bash Scripting · Lesson 18 of 30
Bash Loops
Repeat work with for, while and until loops, read files line by line, and use break and continue.
for
for env in dev staging prod; do echo "deploy to $env"; done
for i in {1..3}; do echo "attempt $i"; done
for (( i = 0; i < 6; i += 2 )); do printf '%s ' "$i"; done; echo
touch a.log b.log
for f in *.log; do echo "found $f"; done
Output
deploy to dev deploy to staging deploy to prod attempt 1 attempt 2 attempt 3 0 2 4 found a.log found b.log
Run this on your computer — see “Get Started” for setup.
while and reading lines
while IFS= read -r line reads input line by line without mangling spaces or backslashes; it's the standard way
to process a file:
cat > hosts.txt <<'EOF'
web-1 10.0.0.11
# web-2 is retired
db-1 10.0.0.21
EOF
while IFS= read -r line; do
[[ $line == \#* || -z $line ]] && continue
read -r name ip <<< "$line"
echo "$name -> $ip"
done < hosts.txt
n=0
until (( n >= 3 )); do (( n++ )); done
echo "until finished at $n"
Output
web-1 -> 10.0.0.11 db-1 -> 10.0.0.21 until finished at 3
Run this on your computer — see “Get Started” for setup.
break leaves a loop and continue skips to the next iteration.
Test yourself
What's the safe way to read a file line by line?
for line in $(cat file)while IFS= read -r line; do ...; done < filecat file | for lineread file
Show answer
Answer: while IFS= read -r line; do ...; done < file
for over $(cat file) splits on spaces, not lines, and expands globs.