Day 5: Bash Scripting – Loops, Functions, Exit Codes

Series: 30 Days DevOps Interview Preparation
Welcome to Day 5 of the 30 Days of DevOps Interview Preparation series. Today we dive into Bash scripting, a critical component of DevOps automation. Mastering Bash allows you to automate infrastructure tasks, system administration, and application deployments efficiently.
🔁 Bash Loops
📘 What is a Loop?
A loop is a control flow statement used to repeat a block of code multiple times. Bash supports multiple types of loops:
➤ for
Loop
for i in {1..5}; do
echo "Iteration $i"
done
This iterates from 1 to 5, echoing each iteration. Useful for bulk tasks like iterating over files or users.
➤ while
Loop
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
Executes while the condition is true.
➤ until
Loop
count=1
until [ $count -gt 5 ]; do
echo "Count: $count"
((count++))
done
Runs until the condition becomes true.
🧠 Real-World Example:
Loop through all .log
files and delete if older than 30 days:
for file in /var/log/*.log; do
if [ $(find "$file" -mtime +30) ]; then
rm "$file"
fi
done
💡 Interview Insight:
Q: How would you use loops to monitor a service every 5 seconds?
while true; do
systemctl is-active nginx
sleep 5
done
🔧 Bash Functions
📘 What is a Function?
A function is a reusable block of code. It helps modularize logic, improve readability, and avoid repetition.
➤ Defining and Calling Functions
say_hello() {
echo "Hello, $1!"
}
say_hello "Tathagat"
➤ Returning Values
add() {
local sum=$(( $1 + $2 ))
echo $sum
}
result=$(add 10 20)
echo "Result: $result"
🧠 Real-World Example:
Define a logging function for reuse:
log_info() {
echo "[INFO] $(date): $1"
}
log_info "Starting deployment..."
💡 Interview Insight:
Q: What is the difference between return
and echo
in a function?
return
exits the function with a status code (numeric)echo
is used to output text, commonly used to return strings
🚪 Exit Codes
📘 What is an Exit Code?
Every command in Bash returns an exit code:
0
= SuccessNon-zero = Failure
This is critical in scripting because it allows conditional branching and error handling.
➤ Checking Exit Code
ls /notfound
echo $?
Output will be non-zero because the directory doesn’t exist.
➤ Use in Conditionals
if cp file.txt /backup/; then
echo "Backup successful"
else
echo "Backup failed"
fi
🧠 Real-World Use:
Abort script on first error:
#!/bin/bash
set -e # Exit if any command fails
💡 Interview Insight:
Q: How do you handle multiple command failures in a script? Use set -euo pipefail
to:
-e
: Exit on error-u
: Error on undefined variables-o pipefail
: Catch errors in piped commands
🧠 Interview Questions & Answers
What are the different types of loops in Bash?
for
,while
, anduntil
loops. Each suited for different scenarios.How do you pass parameters to Bash functions?
Via$1
,$2
, etc. Example:greet() { echo Hello, $1; }
How are exit codes used in scripting?
To determine success/failure and conditionally proceed or halt scripts.What is the purpose of
set -euo pipefail
?
Enforces stricter error handling to avoid silent failures.Can functions return values in Bash?
Functions return numeric values usingreturn
, or strings usingecho
and capturing with$()
📝 Summary Table
Concept | Description | Example Use Case |
for loop | Iterate through a sequence | Loop over files or user list |
while loop | Run until a condition is false | Monitor services or logs |
Functions | Reusable code blocks | Logging, calculations, checks |
Exit codes | Track success/failure of commands | Script flow control, CI automation |
🚀 DevOps Tips
Use logging inside scripts for better debugging.
Make your scripts idempotent (safe to re-run).
Use shebang (
#!/bin/bash
) and make scripts executable (chmod +x script.sh
).Store common functions in a shared
.bashlib
file.
Subscribe to my newsletter
Read articles from Tathagat Gaikwad directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
