On this page
- How does a for loop over a list work?
- How do I loop over files safely?
- How do I count with ranges and C-style loops?
- How do I read a file or command output line by line?
- When should I use while or until?
- How do break and continue work?
- How do I write an endless loop for a simple watcher?
- How can I speed up a loop over many items?
- Questions
How does a for loop over a list work?
A for loop assigns each word of a list to a variable in turn and runs the body once per word. The list can be typed out, come from a glob, or from an array:
for svc in nginx php8.3-fpm redis-server; do
printf '%-14s %s\n' "$svc" "$(systemctl is-active "$svc")"
doneThe output is a small status table with one service per row. The body sits between do and done. With no in part, for arg; do loops over the script arguments, exactly like for arg in "$@". Service names differ between distributions (PHP-FPM is php-fpm on Rocky and Alma, Redis is redis), so adjust the list to what systemctl list-units --type=service shows on your server.
How do I loop over files safely?
Use a glob directly in the list, never the output of ls. Globs keep names with spaces intact, while parsing ls splits them:
shopt -s nullglob
for f in /var/log/myapp/*.log; do
size=$(stat -c %s "$f")
echo "$f: $size bytes"
gzip -k "$f"
donenullglob makes the loop run zero times when nothing matches; without it the loop would run once with the literal text *.log. For a whole tree including subfolders, enable shopt -s globstar and use **/*.log, or let find do the walking and feed the results into a while loop as shown below. Always quote "$f" inside the body.
How do I count with ranges and C-style loops?
Brace expansion creates a fixed range, and the arithmetic form handles ranges that come from variables:
for i in {1..5}; do echo "round $i"; done
for port in {8080..8090..2}; do echo "$port"; done
count=12
for (( i = 1; i <= count; i++ )); do
printf 'node-%02d.example.net\n' "$i"
done
for i in $(seq 0 5 30); do echo "$i"; doneThe brace form cannot use variables, because braces are expanded before variables: {1..$count} stays literal text. In that case use the (( )) form or seq. The third number in {8080..8090..2} is the step. printf with %02d pads numbers with zeros, handy for host names and file names that should sort correctly.
How do I read a file or command output line by line?
Combine while with read. The flags matter: IFS= keeps leading and trailing spaces, and -r stops backslashes being eaten:
while IFS= read -r line; do
[[ -z "$line" || "$line" == \#* ]] && continue
echo "host: $line"
done < /etc/myapp/hosts.txt
while IFS=: read -r user _ uid _ _ home shell; do
(( uid >= 1000 && uid < 60000 )) && echo "$user $home $shell"
done < /etc/passwdThe second loop splits each line of /etc/passwd on colons and lists real user accounts; the underscore is a throwaway variable for unused fields. To loop over command output and still keep variables after the loop, use process substitution rather than a pipe:
total=0
while IFS= read -r -d '' f; do
(( total++ ))
done < <(find /srv -name "*.tmp" -print0)
echo "$total temp files"-print0 with read -d '' separates names by a null byte, so even names containing newlines are safe.
When should I use while or until?
while repeats as long as its command succeeds; until repeats as long as it fails. That makes until a natural fit for waiting on something to come up:
tries=0
until curl -fsS http://127.0.0.1:8080/health >/dev/null; do
(( ++tries >= 30 )) && { echo "gave up after $tries tries" >&2; exit 1; }
sleep 2
done
echo "app is up"
while ss -ltn | grep -q ":5432 "; do
echo "waiting for port 5432 to close"; sleep 1
doneEvery wait loop needs a way out, either a counter as above or a time limit, otherwise a broken service keeps the script spinning forever. For a fixed deadline, timeout 60 bash -c 'until ...; do sleep 2; done' works too.
How do break and continue work?
continue jumps to the next round of the loop, break leaves it entirely. Both accept a number to act on an outer loop when loops are nested:
for dir in /srv/sites/*/; do
[[ -f "$dir/.skip" ]] && continue
for f in "$dir"*.conf; do
if ! grep -q "server_name" "$f"; then
echo "$f has no server_name, stopping"
break 2
fi
done
doneHere a .skip marker file excludes a site, and the first config file without a server_name line stops both loops at once. Keep nesting shallow; when a loop body grows past a screen, move it into a function as described in Functions in Bash.
How do I write an endless loop for a simple watcher?
Use while true (or while :) with a sleep inside, and stop it with Ctrl+C or a break condition:
while true; do
used=$(df --output=pcent / | tail -n 1 | tr -dc "0-9")
if (( used > 90 )); then
logger -t diskwatch "root filesystem at ${used}%"
fi
sleep 300
donelogger writes to the system journal, readable with journalctl -t diskwatch. A loop like this is fine inside tmux for a quick check, but for anything permanent a cron job or systemd timer is cleaner: it survives reboots and does not hold a shell open.
How can I speed up a loop over many items?
Start the slow command in the background with & and wait for the batch, or hand the list to xargs -P, which caps how many run at once:
for host in web1 web2 web3; do
ssh "deploy@$host.example.net" uptime &
done
wait
find /srv/img -name "*.png" -print0 | xargs -0 -P "$(nproc)" -n 1 optipng -quietMatch the parallel count to nproc so a small server is not overloaded. Calling external commands thousands of times is the usual cause of slow loops, so prefer parameter expansion over sed or basename inside the body. The usage monitoring tutorial helps you see how hard a batch job hits CPU.
Questions about for, while and until loops
Why does my loop split file names with spaces?
The list came from unquoted command output such as $(ls). Use a glob like for f in *.txt or a find -print0 plus while read -d '' loop, and quote "$f".
Why does read skip the last line of my file?
The file has no final newline. Write the loop as while IFS= read -r line || [[ -n $line ]]; do to process that last line too.
Can a loop ask for input from the keyboard?
Not with plain read while it is reading a file, because both share standard input. Read the file on another descriptor: while read -r -u 3 line; do ... done 3< file, then read from the keyboard as usual.
How do I loop over two lists at once?
Loop over indexes of an array with for i in "${!a[@]}" and read ${a[i]} and ${b[i]}. See Arrays in Bash.
Does ssh inside a while read loop stop the loop?
Yes, ssh reads the rest of standard input. Add -n (ssh -n host cmd) or redirect < /dev/null so the loop keeps its input.