โ† Back to All Interview Prep Guides
Linux & DevOps Engineering

Shell Scripting Interview Questions: 30 Practical Scenarios

Real-world Bash scripting problems frequently tested in Linux Administrator, SRE, and Cloud DevOps technical interviews. Complete with executable scripts, error handling, and parameter breakdowns.

What Hiring Managers Actually Evaluate in Bash Interviews

When interviewers ask you to write a Bash script on a shared terminal or whiteboard, they are not testing whether you know every obscure flag. They look for defensive engineering practices:

  • Safe Error Handling: Does your script start with set -euo pipefail to prevent running destructive operations on unset variables?
  • Quoting Variables: Do you write "$FILE" to prevent word splitting when directories contain spaces?
  • Cleanup Guarantees: Do you implement trap functions to delete temporary files when scripts exit unexpectedly?
  • Non-Interactive Automation: Do you use batch flags like top -b or df -P so scripts do not stall in automated cron environments?
System Health

Module 1: Server Health, Resource Monitoring & Alerting

1

CPU Usage Threshold Monitor & Automated Process Triage

Scenario: Write an idempotent script that checks if CPU utilization exceeds 85%. If exceeded, identify the top 3 processes by CPU and log an alert with a timestamp.
#!/usr/bin/env bash
set -euo pipefail

THRESHOLD=85
LOG_FILE="/var/log/cpu_monitor.log"

# Calculate current idle percentage and derive CPU usage
CPU_IDLE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print int($1)}')
CPU_USAGE=$((100 - CPU_IDLE))

if [ "$CPU_USAGE" -gt "$THRESHOLD" ]; then
    TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$TIMESTAMP] ALERT: High CPU detected: ${CPU_USAGE}% (Threshold: ${THRESHOLD}%)" >> "$LOG_FILE"
    echo "[$TIMESTAMP] Top 3 processes by CPU consumption:" >> "$LOG_FILE"
    ps -eo pid,ppid,user,%cpu,%mem,comm --sort=-%cpu | head -n 4 >> "$LOG_FILE"
fi

Production Breakdown & Command Analysis:

  • top -bn1 executes top in non-interactive batch mode for a single snapshot, making it safe for automation.
  • sed and awk reliably extract the idle percentage and convert floating point numbers to integer comparisons in Bash.
  • ps -eo specifies custom columnar output sorted by descending CPU percentage to isolate offending processes without interactive latency.

Key Syntax: top -b (batch mode), ps -eo (custom format), sort=-%cpu

2

Filesystem Disk Usage & Inode Exhaustion Monitoring

Scenario: Monitor root and application filesystems for both disk space utilization and inode capacity exceeding 90%. Send an alert notification before disk exhaustion causes database write panics.
#!/usr/bin/env bash
set -euo pipefail

ALERT_THRESHOLD=90

# Check block capacity
df -hP | awk 'NR>1 {print $1, $5, $6}' | while read -r fs usage mount; do
    PERCENT=${usage%%%}
    if [ "$PERCENT" -ge "$ALERT_THRESHOLD" ]; then
        echo "DISK ALERT: Filesystem $fs mounted on $mount is at ${PERCENT}% capacity" >&2
    fi
done

# Check inode capacity (catches zero-byte file leakage)
df -iP | awk 'NR>1 {print $1, $5, $6}' | while read -r fs usage mount; do
    PERCENT=${usage%%%}
    if [ "$PERCENT" -ge "$ALERT_THRESHOLD" ]; then
        echo "INODE ALERT: Filesystem $fs on $mount has exhausted ${PERCENT}% of available inodes" >&2
    fi
done

Production Breakdown & Command Analysis:

  • df -P uses standard POSIX portable output format, preventing multi-line wrapping on long mount names.
  • df -i inspects inode utilization; servers frequently fail from millions of tiny cache files despite having hundreds of gigabytes of free block space.
  • ${usage%%%} strips the percentage sign using native shell parameter expansion, avoiding slow external subshells.

Key Syntax: df -P (POSIX compliance), df -i (inode mode), ${var%%%} (suffix trim)

3

Memory Leak Detection & Automated OOM Safeguard

Scenario: Verify available RAM and swap pressure. If free memory drops below 10% and swap usage exceeds 50%, trigger an alert and record the memory map.
#!/usr/bin/env bash
set -euo pipefail

# Parse /proc/meminfo for reliable kernel-level statistics
MEM_TOTAL=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
MEM_AVAIL=$(awk '/MemAvailable/ {print $2}' /proc/meminfo)
SWAP_TOTAL=$(awk '/SwapTotal/ {print $2}' /proc/meminfo)
SWAP_FREE=$(awk '/SwapFree/ {print $2}' /proc/meminfo)

AVAIL_PCT=$((MEM_AVAIL * 100 / MEM_TOTAL))

if [ "$SWAP_TOTAL" -gt 0 ]; then
    SWAP_USED=$((SWAP_TOTAL - SWAP_FREE))
    SWAP_PCT=$((SWAP_USED * 100 / SWAP_TOTAL))
else
    SWAP_PCT=0
fi

if [ "$AVAIL_PCT" -lt 10 ] && [ "$SWAP_PCT" -gt 50 ]; then
    echo "[$(date -Iseconds)] MEMORY PRESSURE CRITICAL: Available=${AVAIL_PCT}%, Swap=${SWAP_PCT}%" >&2
    ps -eo pid,user,%mem,rss,comm --sort=-rss | head -n 6 >&2
fi

Production Breakdown & Command Analysis:

  • /proc/meminfo provides direct kernel counters; MemAvailable accounts for reclaimable cache/buffer memory unlike MemFree.
  • Integer arithmetic in $((...)) avoids external dc or bc dependencies for lightweight periodic execution.
  • ps -eo with rss displays the Resident Set Size (actual physical RAM used in kilobytes) per process.

Key Syntax: /proc/meminfo (kernel memory counters), ps --sort=-rss (sort by physical memory)

Log Analytics

Module 2: Log Processing, Regex Parsing & Web Traffic Analysis

4

Nginx/Apache Access Log IP Extraction & Rate Limiting Audit

Scenario: Parse an Nginx access log file, extract the top 10 client IP addresses generating HTTP 4xx and 5xx errors, and format the output into a report.
#!/usr/bin/env bash
set -euo pipefail

LOG_FILE="${1:-/var/log/nginx/access.log}"

if [ ! -f "$LOG_FILE" ]; then
    echo "Error: Log file '$LOG_FILE' does not exist." >&2
    exit 1
fi

echo "=== Top 10 IP Addresses Generating 4xx/5xx Errors ==="
awk '$9 ~ /^[45]/ {print $1}' "$LOG_FILE" | \
    sort | \
    uniq -c | \
    sort -rn | \
    head -n 10 | \
    awk '{printf "%-6d requests from IP: %s\n", $1, $2}'

Production Breakdown & Command Analysis:

  • awk '$9 ~ /^[45]/' checks if column 9 (HTTP status code) matches a regex starting with 4 or 5.
  • sort | uniq -c aggregates occurrences into a frequency count.
  • sort -rn sorts counts numerically in reverse descending order to bubble top offenders to the top.

Key Syntax: awk regex match (~), uniq -c (occurrence count), sort -rn (reverse numeric)

5

Failed SSH Login Analysis from /var/log/auth.log

Scenario: Scan system authentication logs for failed password attempts, group them by attacking IP, and identify brute-force thresholds exceeding 20 attempts.
#!/usr/bin/env bash
set -euo pipefail

AUTH_LOG="${1:-/var/log/auth.log}"
THRESHOLD=20

if [ ! -r "$AUTH_LOG" ]; then
    echo "Error: Cannot read $AUTH_LOG (check permissions/sudo)" >&2
    exit 1
fi

echo "=== Potential SSH Brute-Force Attackers (> ${THRESHOLD} failures) ==="
grep -E "Failed password for (invalid user )?" "$AUTH_LOG" | \
    grep -oE "from [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" | \
    awk '{print $2}' | \
    sort | \
    uniq -c | \
    while read -r count ip; do
        if [ "$count" -ge "$THRESHOLD" ]; then
            printf "CRITICAL: %4d failed attempts from IP: %s\n" "$count" "$ip"
        fi
    done

Production Breakdown & Command Analysis:

  • grep -E applies extended regular expressions to match both valid and invalid user failure records.
  • grep -oE extracts only the matched string (from <IP>), isolating network addresses without noise.
  • The shell loop evaluates numerical thresholds dynamically to filter out occasional user typing mistakes.

Key Syntax: grep -E (extended regex), grep -o (only matching), awk column extraction

6

Multi-Directory Automated Log Archive & Retention Purge

Scenario: Write an enterprise log rotation script that compresses all .log files older than 7 days, moves them to a cold storage mount, and deletes archives older than 60 days.
#!/usr/bin/env bash
set -euo pipefail

SRC_DIR="/var/log/apps"
ARCHIVE_DIR="/mnt/backup/log_archives"
mkdir -p "$ARCHIVE_DIR"

# 1. Compress and archive logs modified more than 7 days ago
find "$SRC_DIR" -type f -name "*.log" -mtime +7 | while read -r logfile; do
    DATE_TAG=$(date -r "$logfile" '+%Y%m%d')
    BASENAME=$(basename "$logfile" .log)
    TARGET="${ARCHIVE_DIR}/${BASENAME}_${DATE_TAG}.tar.gz"
    
    tar -czf "$TARGET" -C "$(dirname "$logfile")" "$(basename "$logfile")"
    rm -f "$logfile"
    echo "Archived $logfile -> $TARGET"
done

# 2. Prune cold storage archives older than 60 days
find "$ARCHIVE_DIR" -type f -name "*.tar.gz" -mtime +60 -delete
echo "Purge of archives older than 60 days completed."

Production Breakdown & Command Analysis:

  • find with -mtime +7 matches files where modification timestamps exceed 7 full 24-hour intervals.
  • tar -czf compresses directly using gzip while -C ensures tar archives do not capture leading directory paths.
  • -delete safely removes matched files at the filesystem layer without invoking subshells.

Key Syntax: find -mtime (modification age), tar -C (change directory), find -delete

Process Management

Module 3: Process Supervision, Resilience & Automated Self-Healing

7

Daemon Watchdog with Auto-Restart & Exponential Backoff

Scenario: Supervise an essential background service. If the process terminates, attempt an automated restart with exponential backoff up to a maximum of 3 attempts before paging the team.
#!/usr/bin/env bash
set -euo pipefail

SERVICE_NAME="payment-worker"
MAX_ATTEMPTS=3
DELAY=2

is_running() {
    pgrep -f "$SERVICE_NAME" > /dev/null 2>&1
}

attempt=1
while [ "$attempt" -le "$MAX_ATTEMPTS" ]; do
    if is_running; then
        echo "Service '$SERVICE_NAME' is running normally."
        exit 0
    fi

    echo "WARNING: '$SERVICE_NAME' is down. Attempting restart ($attempt/$MAX_ATTEMPTS)..." >&2
    systemctl restart "$SERVICE_NAME" || true
    sleep "$DELAY"

    if is_running; then
        echo "SUCCESS: '$SERVICE_NAME' restarted successfully."
        exit 0
    fi

    DELAY=$((DELAY * 2))
    attempt=$((attempt + 1))
done

echo "FATAL: '$SERVICE_NAME' failed to start after $MAX_ATTEMPTS attempts. Paging on-call." >&2
exit 1

Production Breakdown & Command Analysis:

  • pgrep -f searches the full process command line rather than just the 15-character comm name limit.
  • Exponential backoff (DELAY=$((DELAY * 2))) prevents overloading a system that is failing due to database connection throttling.
  • Exiting with status code 1 allows external supervisors like systemd or Nagios to detect watchdog failure.

Key Syntax: pgrep -f (full command regex), systemctl restart, exponential backoff loop

8

Automated Termination of Rogue & Runaway Processes (>80% CPU)

Scenario: Safely identify processes consuming more than 80% CPU for more than 5 consecutive minutes. Send SIGTERM first, followed by SIGKILL if the process fails to exit gracefully.
#!/usr/bin/env bash
set -euo pipefail

THRESHOLD=80.0
WHITELIST_USERS="root|systemd-resolve"

# Extract PID, User, CPU%, and command
ps -eo pid,user,%cpu,comm --sort=-%cpu | awk 'NR>1 {print $1, $2, $3, $4}' | while read -r pid user cpu comm; do
    # Skip whitelisted system users
    if echo "$user" | grep -Eq "$WHITELIST_USERS"; then
        continue
    fi

    # Check if CPU exceeds threshold
    EXCEEDS=$(awk -v c="$cpu" -v t="$THRESHOLD" 'BEGIN {print (c > t) ? 1 : 0}')
    if [ "$EXCEEDS" -eq 1 ]; then
        echo "Terminating runaway process: PID=$pid ($comm) owned by $user consuming ${cpu}% CPU"
        kill -15 "$pid" 2>/dev/null || true
        sleep 5
        
        # Verify if still alive, then SIGKILL
        if kill -0 "$pid" 2>/dev/null; then
            echo "PID $pid refused SIGTERM. Issuing SIGKILL (kill -9)"
            kill -9 "$pid" 2>/dev/null || true
        fi
    fi
done

Production Breakdown & Command Analysis:

  • kill -0 sends a null signal that performs error checking without actually delivering a signal; it tests if a PID is alive.
  • Sending SIGTERM (-15) first allows application threads to flush file buffers and close database sockets cleanly.
  • awk -v passes shell variables directly into awk for safe floating-point comparison.

Key Syntax: kill -0 (PID alive check), kill -15 (SIGTERM), kill -9 (SIGKILL)

Network Engineering

Module 4: Network Diagnostics, TLS Certificate Checks & Remote Port Auditing

9

TLS/SSL Certificate Expiration Validator

Scenario: Connect to an external HTTPS endpoint, extract the TLS certificate expiration date, and alert if expiration is within 14 days.
#!/usr/bin/env bash
set -euo pipefail

DOMAIN="${1:-api.getjobwithabu.com}"
PORT="${2:-443}"
WARN_DAYS=14

# Fetch certificate expiration via OpenSSL s_client
EXPIRY_DATE=$(echo | openssl s_client -servername "$DOMAIN" -connect "${DOMAIN}:${PORT}" 2>/dev/null | \
    openssl x509 -noout -enddate | \
    cut -d= -f2)

if [ -z "$EXPIRY_DATE" ]; then
    echo "ERROR: Could not retrieve TLS certificate for ${DOMAIN}:${PORT}" >&2
    exit 2
fi

EXPIRY_EPOCH=$(date -d "$EXPIRY_DATE" +%s)
NOW_EPOCH=$(date +%s)
DAYS_LEFT=$(( (EXPIRY_EPOCH - NOW_EPOCH) / 86400 ))

echo "Certificate for $DOMAIN expires on: $EXPIRY_DATE ($DAYS_LEFT days remaining)"

if [ "$DAYS_LEFT" -le "$WARN_DAYS" ]; then
    echo "ALERT: Certificate for $DOMAIN expires in $DAYS_LEFT days! Renew immediately." >&2
    exit 1
fi

Production Breakdown & Command Analysis:

  • openssl s_client with -servername guarantees proper SNI (Server Name Indication) routing on multi-tenant load balancers.
  • openssl x509 -enddate parses and outputs the NotAfter validity timestamp.
  • Epoch calculation converts date strings into seconds since 1970 for exact integer mathematical comparison.

Key Syntax: openssl s_client -servername (SNI), openssl x509 -enddate, date -d +%s

10

Multi-Host Port Connectivity Audit with Strict Timeout

Scenario: Verify if a cluster of remote databases and cache endpoints are accepting connections on specified ports using netcat or bash TCP sockets without hanging indefinitely.
#!/usr/bin/env bash
set -euo pipefail

HOSTS=(
    "db-primary.internal:5432"
    "redis-cache.internal:6379"
    "auth-service.internal:8080"
)
TIMEOUT=3

for entry in "${HOSTS[@]}"; do
    HOST="${entry%%:*}"
    PORT="${entry##*:}"

    if timeout "$TIMEOUT" bash -c "</dev/tcp/$HOST/$PORT" 2>/dev/null; then
        printf "[OK] Connected to %s on port %s\n" "$HOST" "$PORT"
    else
        printf "[FAIL] Connection to %s on port %s TIMED OUT or REFUSED\n" "$HOST" "$PORT" >&2
    fi
done

Production Breakdown & Command Analysis:

  • /dev/tcp/host/port is a native Bash built-in feature that tests raw TCP socket connections without needing third-party tools.
  • timeout restricts socket connection latency, preventing automation scripts from stalling on dropped packets.
  • ${entry%%:*} and ${entry##*:} perform parameter prefix and suffix trimming without external cut invocations.

Key Syntax: timeout <sec>, /dev/tcp/<host>/<port> (native socket), parameter expansion

Automation Runbooks

Module 5: Defensive Automation, Atomic Backups & Clean Execution

11

Defensive Scripting Framework with Cleanup Traps & Signal Handling

Scenario: Implement a production template utilizing set -euo pipefail, an automated trap function for cleaning temporary files, and ISO-8601 logging.
#!/usr/bin/env bash
# Production Defensive Automation Template
set -euo pipefail

TMP_DIR=$(mktemp -d /tmp/deploy_payload.XXXXXX)

cleanup() {
    local exit_code=$?
    echo "[$(date -Iseconds)] Cleaning up temporary workspace: $TMP_DIR"
    rm -rf "$TMP_DIR"
    exit "$exit_code"
}
trap cleanup EXIT INT TERM

log() {
    echo "[$(date '+%Y-%m-%dT%H:%M:%S%z')] $*"
}

log "INFO: Initialized deployment runbook in $TMP_DIR"
# Perform sensitive operations here safely...
log "INFO: Completed all pipeline stages cleanly."

Production Breakdown & Command Analysis:

  • set -e halts execution on error; -u treats unset variables as fatal errors; -o pipefail preserves pipeline error status.
  • trap cleanup EXIT INT TERM ensures temporary files are guaranteed to be purged even if the script is interrupted with Ctrl+C.
  • mktemp -d generates unique, non-guessable temporary directories preventing race conditions and symlink attacks.

Key Syntax: set -euo pipefail, trap <fn> EXIT INT TERM, mktemp -d

12

Automated Database Backup with Integrity Check & Checksum Verification

Scenario: Dump a database, compress it with gzip, generate an SHA-256 checksum for verification, and test archive integrity.
#!/usr/bin/env bash
set -euo pipefail

BACKUP_DIR="/var/backups/db"
TIMESTAMP=$(date '+%Y%m%d_%H%M%S')
BACKUP_FILE="${BACKUP_DIR}/dump_${TIMESTAMP}.sql.gz"
mkdir -p "$BACKUP_DIR"

echo "Beginning database export to $BACKUP_FILE..."
# Example mysqldump piped through gzip
mysqldump --single-transaction --quick --databases app_db | gzip -9 > "$BACKUP_FILE"

# Verify gzip archive integrity
if ! gzip -t "$BACKUP_FILE"; then
    echo "ERROR: Backup archive is corrupted!" >&2
    rm -f "$BACKUP_FILE"
    exit 1
fi

# Generate SHA256 checksum for audit and replication tracking
sha256sum "$BACKUP_FILE" > "${BACKUP_FILE}.sha256"
echo "Backup and SHA-256 checksum generated successfully: ${BACKUP_FILE}"

Production Breakdown & Command Analysis:

  • --single-transaction executes backup inside a consistent snapshot without locking InnoDB tables during production writes.
  • gzip -t tests the integrity of the compressed archive before the original data is touched or rotated.
  • sha256sum provides cryptographic verification when shipping backups across network mounts or cloud object storage.

Key Syntax: mysqldump --single-transaction, gzip -t (integrity test), sha256sum

Abu - Founder of GetJobWithAbu

Abu

Founder of GetJobWithAbuCloud & Azure Developer (5+ Years IT Exp)

Cloud & Azure Developer with 5+ years of IT industry experience, having transitioned from a 4.8-year IT Support role into Software & Cloud Development. Dedicated to helping freshers, Tier-2/Tier-3 college graduates, and IT support engineers crack technical interviews through practical production insights, real-world scenario questions, and hands-on guidance.