Loops: Iterating with for and while in Bash
Loops allow scripts to repeat operations over lists of files, lines, or until a condition changes.
1. The for Loop
Iterate over a list of items or files:
#!/bin/bash
# Loop over a list of server names
SERVERS=("web-01" "web-02" "web-03")
for server in "${SERVERS[@]}"; do
echo "Pinging $server..."
ping -c 1 "$server" > /dev/null && echo "$server is up" || echo "$server is down"
doneIterating Over Files
#!/bin/bash
# Process all .log files in the current directory
for logfile in /var/log/*.log; do
echo "Rotating: $logfile"
gzip "$logfile"
done2. The while Loop
Continue looping while a condition remains true:
#!/bin/bash
# Retry a command up to 5 times before giving up
RETRIES=0
MAX_RETRIES=5
while [ $RETRIES -lt $MAX_RETRIES ]; do
if curl -s https://api.example.com/health | grep -q "ok"; then
echo "Service is healthy!"
break
fi
RETRIES=$((RETRIES + 1))
echo "Attempt $RETRIES failed. Retrying in 5 seconds..."
sleep 5
done
if [ $RETRIES -eq $MAX_RETRIES ]; then
echo "ERROR: Service failed to respond after $MAX_RETRIES attempts."
exit 1
fiPublished on Last updated: