for & while Loops
Loops repeat commands — for iterates over a list, while repeats until a condition fails.
Syntax
for x in list; do ... done
while [ condition ]; do ... doneLoops let a script do the same work many times.
for loops
A for loop walks through a list of items — words, files from a glob, or a number range.
for item in a b c; do
echo "$item"
donewhile loops
A while loop keeps going as long as its condition holds. It is ideal for reading a file line by line, or waiting for something to become ready.
Example
#!/bin/bash
# Loop over a list
for name in Alice Bob Carol; do
echo "Hello, $name"
done
# Loop over files
for f in *.log; do
echo "Compressing $f"
gzip "$f"
done
# Count down with while
n=3
while [ "$n" -gt 0 ]; do
echo "$n..."
n=$((n - 1))
doneWhen to use it
- A sysadmin uses a for loop to restart nginx on 20 servers in sequence: 'for s in $(cat servers.txt); do ssh $s systemctl restart nginx; done'.
- A script uses a while loop to wait for a service port to open before continuing a deployment: 'while ! nc -z localhost 8080; do sleep 2; done'.
- A developer uses a for loop with a glob to process every CSV in a directory: 'for f in data/*.csv; do python3 import.py "$f"; done'.
More examples
For loop over a list
Iterates a fixed list of servers, pinging each one and reporting its status with && / || branching.
#!/bin/bash
for server in web1 web2 web3; do
echo "Checking $server..."
ping -c 1 -q "$server" && echo " UP" || echo " DOWN"
doneFor loop over files
Loops over a glob pattern to process multiple files, using command substitution to get each file's size.
#!/bin/bash
# Process every .log file in a directory
for logfile in /var/log/nginx/*.log; do
SIZE=$(du -sh "$logfile" | cut -f1)
echo "$logfile: $SIZE"
doneWhile loop waiting for a port
Uses a while loop with nc to poll a TCP port and block until the application is ready to accept connections.
#!/bin/bash
echo "Waiting for app to start..."
while ! nc -z localhost 8080; do
sleep 2
done
echo "App is ready on port 8080"
Discussion