Bash Scripting Interview Questions: What SRE and DevOps Roles Actually Ask
Q1: Write a retry function that retries a command up to N times.
retry() {
local max="$1" delay="$2"; shift 2
local attempt=1
until "$@"; do
[ "$attempt" -ge "$max" ] && { echo "Failed after $max attempts" >&2; return 1; }
echo "Attempt $attempt failed. Retrying in ${delay}s..."
sleep "$delay"; ((attempt++))
done
}
retry 5 2 curl -sf https://api.example.com/health
---
Q2: Find and kill all processes matching a name.
pkill -f "python3 worker.py"
# Manual (for understanding)
ps aux | grep "[p]ython3 worker.py" | awk '{print $2}' | xargs kill -15
The [p] trick prevents grep from matching itself.
---
Q3: What does set -euo pipefail do? When would you NOT use it?
-e: exit immediately on any error-u: treat unset variables as errors-o pipefail: pipe exit code is the last non-zero exit code
Avoid in: .bashrc (breaks interactive sessions), scripts that handle failures inline.
---
Q4: Sum a column in a CSV file.
awk -F',' 'NR>1 {sum += $2} END {print sum}' data.csv
# Filter to only "completed" rows
awk -F',' 'NR>1 && $3=="completed" {sum += $2} END {print sum}' data.csv
---
Q5: Monitor disk usage and alert if any filesystem exceeds 80%.
#!/usr/bin/env bash
THRESHOLD=80
df -h --output=pcent,target | tail -n +2 | while read -r usage mount; do
pct="${usage%%%}"
if [ "$pct" -ge "$THRESHOLD" ]; then
echo "ALERT: $mount is at ${usage} on $(hostname)" >&2
fi
done
---
Q6: How do you safely use a temporary file?
tmpfile=$(mktemp)
trap "rm -f $tmpfile" EXIT # cleanup on any exit
some_command > "$tmpfile"
process_results "$tmpfile"
---
Q7: Difference between [ and [[.
[ is POSIX-compatible (test command). [[ is bash-only but supports pattern matching ([[ $file == *.log ]]), regex (=~), no word splitting on unquoted variables, and &&/|| inside the brackets.
---
Q8: Run a script on 20 servers in parallel with throttling.
MAX_PARALLEL=5
for host in web{01..20}; do
ssh "$host" "sudo systemctl restart myapp" &
while [ "$(jobs -r | wc -l)" -ge "$MAX_PARALLEL" ]; do sleep 0.5; done
done
wait
---
Q9: Extract the HTTP status code from curl.
status=$(curl -o /dev/null -s -w "%{http_code}" https://api.example.com/health)
[ "$status" -ne 200 ] && { echo "Unexpected: $status" >&2; exit 1; }
---
Q10: A script works manually but fails in cron. What do you check?
- PATH - use absolute paths or set PATH explicitly in the crontab
- Working directory - cron starts in
$HOME, not the script's directory - Environment variables - source
/etc/environmentif needed - Permissions - is the script executable? Can the cron user access all files?
- Output - add
>> /tmp/script.log 2>&1to see what fails - Test as cron user -
sudo -u cronuser env -i HOME=/home/cronuser /opt/script.sh
Practice in the ShellGenius Linux Labs — the bash-scripting and bash-parallel-pipeline challenges use real multi-step scenarios.