Skip to content
$ lynuxpro
← Bash Scripting

LESSON 5 OF 17 · BEGINNER · 18 MIN

Loops

HOW IT WORKSfor and while loops

web1Listweb1 web2 db1for host in …one per itemLoop bodyping, ssh, curlservers.csvline by linewhile read -runtil EOFbreak / continueskip or stop
1/5

for walks a list of words: hosts, files from a glob, or numbers from {1..5}.

for host in web1 web2 db1; do

The real power of scripting shows up when the same action has to happen many times: check ten servers, compress every log file, retry a request until it works, read a CSV line by line. Loops do that. Bash has three you will use constantly: for, while and until, plus break and continue to control them.

In simple words

  • Loop: repeats commands, either for each item in a list or while something is true.
  • for: runs once for each item: each file, server or number.
  • while: keeps running as long as a command succeeds. Often used to read a file line by line.
  • break / continue: break leaves the loop. continue skips to the next round.

for over a list of words

for runs its body once for each word in a list, setting a variable each time:

for host in web1 web2 db1; do echo "checking $host"; done
SHELLbashutf-8 · 1L
checking web1checking web2checking db1
OUTPUTterminalutf-8 · 3L

In a script you write it over several lines:

for host in web1 web2 db1; do  echo "checking $host"  ping -c 1 "$host"done
SHELLbashutf-8 · 4L

The list can come from many places:

for n in {1..5}; do echo -n "$n "; done; echofor f in /var/log/*; do echo "found: $f"; doneservers=(web1 web2 db1)for s in "${servers[@]}"; do echo "server: $s"; done
SHELLbashutf-8 · 4L
1 2 3 4 5 found: /var/log/appfound: /var/log/nginxfound: /var/log/syslogserver: web1server: web2server: db1
OUTPUTterminalutf-8 · 7L
  • {1..5} is brace expansion. {01..10} pads with zeros and {0..20..5} steps by 5.
  • /var/log/* is a glob: Bash replaces it with matching file names, already safely split, even if names contain spaces.
  • "${servers[@]}" loops over an array (arrays are covered in detail in lesson 7).

C-style for

When you need a counter, Bash also supports the C-style form with arithmetic:

for ((i = 1; i <= 3; i++)); do echo "attempt $i"; done
SHELLbashutf-8 · 1L
attempt 1attempt 2attempt 3
OUTPUTterminalutf-8 · 3L

Do not loop over $(ls) or $(cat file)

This is the classic beginner bug:

for f in $(ls /data); do     # WRONG: splits "my report.txt" into two items  gzip "$f"done for f in /data/*; do         # RIGHT: the glob keeps each name whole  gzip "$f"done
SHELLbashutf-8 · 7L

The same goes for reading lines of a file: for line in $(cat hosts.txt) loops over words, not lines. Use while read, shown next.

while: repeat while a command succeeds

while runs its body as long as its condition command exits 0. Just like if, the condition is any command:

count=1while [[ $count -le 3 ]]; do echo "count is $count"; count=$((count + 1)); done
SHELLbashutf-8 · 2L
count is 1count is 2count is 3
OUTPUTterminalutf-8 · 3L

until is the opposite: it loops until the command succeeds. It reads naturally for waiting:

until curl -fsS http://localhost:8080/health > /dev/null; do  echo "waiting for the app..."  sleep 2doneecho "app is up"
SHELLbashutf-8 · 5L

Reading a file line by line

while read is the correct way to process a file one line at a time:

while read -r ip name; do echo "$name has address $ip"; done < /etc/hosts
SHELLbashutf-8 · 1L
localhost has address 127.0.0.1web1 has address 10.0.1.10web2 has address 10.0.1.11db1 has address 10.0.2.10
OUTPUTterminalutf-8 · 4L

How it works:

  • < /etc/hosts after done feeds the file into the whole loop.
  • Each read -r ip name consumes one line, splitting it on spaces into the variables; the last variable gets the rest of the line.
  • When the file ends, read returns a non-zero exit code and the loop stops.

For CSV files, set IFS (the field separator) for the read command only:

cat servers.csvwhile IFS=, read -r name env ip cpu; do echo "$name ($env) at $ip with $cpu CPUs"; done < servers.csv
SHELLbashutf-8 · 2L
name,env,ip,cpuweb1,prod,10.0.1.10,4web2,prod,10.0.1.11,4db1,prod,10.0.2.10,8web-stg,staging,10.1.1.10,2ci-runner,tools,10.2.0.5,16name (env) at ip with cpu CPUsweb1 (prod) at 10.0.1.10 with 4 CPUsweb2 (prod) at 10.0.1.11 with 4 CPUsdb1 (prod) at 10.0.2.10 with 8 CPUsweb-stg (staging) at 10.1.1.10 with 2 CPUsci-runner (tools) at 10.2.0.5 with 16 CPUs
OUTPUTterminalutf-8 · 12L

The header line was treated as data. That is what continue is for.

continue and break

  • continue skips the rest of the body and moves to the next item.
  • break leaves the loop completely.

Skip the header and anything that is not production:

while IFS=, read -r name env ip cpu; do [[ $name == name ]] && continue; [[ $env == prod ]] || continue; echo "prod server: $name"; done < servers.csv
SHELLbashutf-8 · 1L
prod server: web1prod server: web2prod server: db1
OUTPUTterminalutf-8 · 3L

Stop at the first error line in a log:

while read -r line; do if [[ $line == *ERROR* ]]; then echo "first error: $line"; break; fi; done < /var/log/app/app.log
SHELLbashutf-8 · 1L
first error: 2026-11-28T09:06:02Z ERROR database connection timeout host=db1
OUTPUTterminalutf-8 · 1L

Loops and pipes

You can pipe into a loop, which is useful when the data comes from a command:

grep ERROR /var/log/app/app.log | while read -r ts level msg; do echo "[$level] $msg"; done
SHELLbashutf-8 · 1L
[ERROR] database connection timeout host=db1[ERROR] payment service returned 503
OUTPUTterminalutf-8 · 2L

One catch: in Bash, each part of a pipeline runs in a subshell, so variables set inside a piped while loop are lost after it. If you need a total afterwards, redirect from the command with process substitution instead (you will see < <(command) again in lesson 15):

errors=0while read -r line; do errors=$((errors + 1)); done < <(grep ERROR /var/log/app/app.log)echo "errors: $errors"
SHELLbashutf-8 · 3L
errors: 2
OUTPUTterminalutf-8 · 1L

A retry loop

Networks fail. Good automation retries with a delay and gives up after a limit:

#!/usr/bin/env bashurl=${1:?usage: $0 URL}max=5for ((attempt = 1; attempt <= max; attempt++)); do  if curl -fsS "$url" > /dev/null; then    echo "OK after $attempt attempt(s)"    exit 0  fi  delay=$((attempt * 2))  echo "attempt $attempt failed, retrying in ${delay}s" >&2  sleep "$delay"doneecho "giving up after $max attempts" >&2exit 1
SHELLbashutf-8 · 14L

The delay grows each time (2, 4, 6 … seconds), which is gentler on a struggling service than hammering it.

Real-world scenario: rotate old logs

Every night a script compresses yesterday's application logs and reports how many it handled:

#!/usr/bin/env bashcd /var/log/myapp || exit 1count=0for f in *.log; do  [[ -e $f ]] || continue          # no .log files: the glob stays literal  [[ $f == current.log ]] && continue  gzip -9 "$f"  count=$((count + 1))doneecho "compressed $count log file(s)"
SHELLbashutf-8 · 10L

The [[ -e $f ]] || continue line handles an important edge case: if no file matches *.log, Bash leaves the pattern as the literal text *.log, and without the check the script would try to gzip a file with that name.

Common mistakes

  • for line in $(cat file): loops over words, not lines. Use while read -r.
  • Missing -r on read: backslashes disappear.
  • Forgetting do or done, or putting ; in the wrong place in one-liners: for x in a b; do echo $x; done.
  • Expecting variables from a piped while to survive: use < <(cmd) or < file instead.
  • Infinite loops: a while whose condition never changes. Always make sure something in the body moves toward the end, or add a maximum.
  • Unquoted loop variables: rm $f instead of rm "$f".

Practice

  1. Print the numbers 10, 20, … 100 with brace expansion.
  2. Loop over every file in /etc that ends in .conf (if there are none, make sure your loop prints nothing).
  3. Read /etc/passwd with IFS=: and print the user name and shell of every user whose shell is /bin/bash.
  4. Count the lines in /var/log/nginx/access.log that contain 500 using a while read loop, and print the total after the loop.
  5. Write an until loop that counts down from 5 to 1.

Cheat sheet

for x in a b c; do …; done          list of wordsfor f in /path/*.log; do …; done    files (safe with spaces)for n in {1..10}; do …; done        number rangefor ((i=0; i<5; i++)); do …; done   counterwhile cmd; do …; done               while cmd succeedsuntil cmd; do …; done               until cmd succeedswhile read -r a b; do …; done < file        lines of a filewhile IFS=, read -r a b c; do …; done < f   CSVwhile read -r l; do …; done < <(cmd)        lines of a command, vars survivecontinue / break                    skip item / leave loop
OUTPUTterminalutf-8 · 10L

Key takeaways

  • for loops over words, globs, ranges or arrays; use globs, never $(ls), for files.
  • while and until repeat based on a command's exit code, like if.
  • while IFS=… read -r …; do …; done < file is the right way to process lines and CSV.
  • continue skips an item and break stops the loop.
  • Variables set in a piped loop are lost; redirect with < <(command) when you need them afterwards.