DevOps Blog

Bash Loops for Beginners: A Simple Guide for DevOps Tasks

If you're new to Bash scripting, loops are one of the most powerful tools you can learn. They help automate repetitive tasks, making your work as a DevOps engineer much more efficient.

In this guide, we'll cover the basics of for and while loops in Bash, along with practical examples you might use in real-world DevOps scenarios.


1. What Are Loops?

Loops allow you to repeat a block of code multiple times. The two most common types in Bash are:

  • for loops – Run a command for each item in a list.
  • while loops – Run a command as long as a condition is true.

2. The for Loop

Basic Syntax

for item in list_of_items; do commands done

Example 1: Looping Through Files

A common DevOps task is processing multiple files, like logs or configs.

for file in /var/log/*.log; do echo "Processing: $file" grep "error" "$file" > "${file}.errors" done

This loop:

  • Finds all .log files in /var/log/
  • Searches for the word "error" in each file
  • Saves results to a new .errors file

Example 2: Iterating Over a List

You might need to loop through a list of servers to run a command.

servers=("web1" "web2" "db1") for server in "${servers[@]}"; do echo "Restarting $server..." ssh "admin@$server" "sudo systemctl restart nginx" done

This:

  • Connects to each server via SSH
  • Restarts the Nginx service

3. The while Loop

Basic Syntax

while [ condition ]; do commands done

Example 1: Running Until a Condition Is Met

Check if a service is up before proceeding.

count=0 while ! curl -s http://localhost:80 > /dev/null; do echo "Waiting for web server..." sleep 5 ((count++)) if [ $count -gt 10 ]; then echo "Server not responding after 10 attempts!" exit 1 fi done echo "Server is up!"

This:

  • Keeps checking port 80 until the server responds
  • Fails after 10 attempts

Example 2: Reading a File Line by Line

Process a list of users from a file.

while IFS= read -r user; do echo "Creating account for $user" useradd "$user" done < users.txt

This:

  • Reads users.txt line by line
  • Creates a Linux user for each name

4. Common DevOps Use Cases for Loops

  1. Batch Processing Files – Rename, compress, or analyze logs.
  2. Automating Server Tasks – Deploying configs, restarting services.
  3. Health Checks – Monitoring until a condition is met.
  4. Scaling Operations – Running commands across multiple containers/VMs.

5. Key Takeaways

for loops are great for known lists (files, servers, etc.).
while loops are useful for conditions (waiting, retrying).
Loops save time by automating repetitive tasks.

Now that you know the basics, try writing your own loops to simplify your DevOps workflows!

Got questions? Drop them in the comments!