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?

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?

  1. PATH - use absolute paths or set PATH explicitly in the crontab
  2. Working directory - cron starts in $HOME, not the script's directory
  3. Environment variables - source /etc/environment if needed
  4. Permissions - is the script executable? Can the cron user access all files?
  5. Output - add >> /tmp/script.log 2>&1 to see what fails
  6. 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.