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.

Create a free account to save this page, take notes and track your progress. Sign in

for

for loops
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:

while read and until
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?

  1. for line in $(cat file)
  2. while IFS= read -r line; do ...; done < file
  3. cat file | for line
  4. read file
Show answer

Answer: while IFS= read -r line; do ...; done < file

for over $(cat file) splits on spaces, not lines, and expands globs.

Was this page helpful?