Linux interview question · Most asked

Write a script that alerts when disk usage passes a threshold.

Hands-on Asked in DevOps Engineer · Site Reliability Engineer (SRE) interviews

Members can save this page, take notes and track progress. See membership · Sign in

Summary

Read usage per filesystem with df, compare with a threshold, and send an alert (log, email, Slack webhook) for each filesystem over it. Exit non-zero when something is over, so cron, systemd or a monitoring agent can act on the result. In production you'd normally alert from your monitoring system, but the script shows fundamentals.

Longer Answer

Points interviewers check:

  • Parse df output safely (-P for POSIX format, skip pseudo-filesystems such as tmpfs).
  • Make the threshold configurable.
  • Check inodes too (df -i): a disk can be "full" with free space when it runs out of inodes.
  • Avoid alert storms: alert once per state change or let the monitoring system deduplicate.
  • set -euo pipefail in Bash, and quoting variables.

Example

#!/usr/bin/env bash
set -euo pipefail
THRESHOLD="${1:-85}"
WEBHOOK="${ALERT_WEBHOOK:-}"
status=0
while read -r fs size used avail pct mount; do
  usage="${pct%\%}"
  if (( usage >= THRESHOLD )); then
    msg="$(hostname): ${mount} is ${usage}% full (${avail} left)"
    echo "$msg" >&2
    [[ -n "$WEBHOOK" ]] && curl -fsS -X POST -H 'Content-Type: application/json' \
      -d "{\"text\": \"${msg}\"}" "$WEBHOOK" >/dev/null
    status=1
  fi
done < <(df -P -x tmpfs -x devtmpfs -x overlay | tail -n +2)
exit "$status"
import shutil, socket, sys
THRESHOLD = int(sys.argv[1]) if len(sys.argv) > 1 else 85
over = []
for mount in ("/", "/var", "/data"):
    u = shutil.disk_usage(mount)
    pct = u.used * 100 // u.total
    if pct >= THRESHOLD:
        over.append(f"{socket.gethostname()}: {mount} is {pct}% full")
print("\n".join(over) or "ok")
sys.exit(1 if over else 0)

Key Points

  • Use df -P and skip pseudo-filesystems.
  • Configurable threshold; non-zero exit on breach.
  • Check inodes as well as blocks.
  • Prefer monitoring-system alerts in production.

Explanation

What interviewers look for

Correct parsing, sensible exit codes and the inode edge case; a Python version is equally fine.

More Linux questions

← All Linux questions

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake