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.
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.for
Loopfor item in list_of_items; do
commands
done
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:
.log
files in /var/log/
.errors
fileYou 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:
while
Loopwhile [ condition ]; do
commands
done
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:
80
until the server respondsProcess a list of users from a file.
while IFS= read -r user; do
echo "Creating account for $user"
useradd "$user"
done < users.txt
This:
users.txt
line by linefor
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!