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"; donechecking web1checking web2checking db1In a script you write it over several lines:
for host in web1 web2 db1; do echo "checking $host" ping -c 1 "$host"doneThe 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"; done1 2 3 4 5 found: /var/log/appfound: /var/log/nginxfound: /var/log/syslogserver: web1server: web2server: db1{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"; doneattempt 1attempt 2attempt 3Do 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"doneThe 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)); donecount is 1count is 2count is 3until 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"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/hostslocalhost has address 127.0.0.1web1 has address 10.0.1.10web2 has address 10.0.1.11db1 has address 10.0.2.10How it works:
< /etc/hostsafterdonefeeds the file into the whole loop.- Each
read -r ip nameconsumes one line, splitting it on spaces into the variables; the last variable gets the rest of the line. - When the file ends,
readreturns 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.csvname,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 CPUsThe header line was treated as data. That is what continue is for.
continue and break
continueskips the rest of the body and moves to the next item.breakleaves 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.csvprod server: web1prod server: web2prod server: db1Stop 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.logfirst error: 2026-11-28T09:06:02Z ERROR database connection timeout host=db1Loops 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[ERROR] database connection timeout host=db1[ERROR] payment service returned 503One 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"errors: 2A 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 1The 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)"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. Usewhile read -r.- Missing
-ronread: backslashes disappear. - Forgetting
doordone, or putting;in the wrong place in one-liners:for x in a b; do echo $x; done. - Expecting variables from a piped
whileto survive: use< <(cmd)or< fileinstead. - Infinite loops: a
whilewhose condition never changes. Always make sure something in the body moves toward the end, or add a maximum. - Unquoted loop variables:
rm $finstead ofrm "$f".
Practice
- Print the numbers 10, 20, … 100 with brace expansion.
- Loop over every file in
/etcthat ends in.conf(if there are none, make sure your loop prints nothing). - Read
/etc/passwdwithIFS=:and print the user name and shell of every user whose shell is/bin/bash. - Count the lines in
/var/log/nginx/access.logthat contain500using awhile readloop, and print the total after the loop. - Write an
untilloop 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 loopKey takeaways
forloops over words, globs, ranges or arrays; use globs, never$(ls), for files.whileanduntilrepeat based on a command's exit code, likeif.while IFS=… read -r …; do …; done < fileis the right way to process lines and CSV.continueskips an item andbreakstops the loop.- Variables set in a piped loop are lost; redirect with
< <(command)when you need them afterwards.