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
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
dfoutput safely (-Pfor 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 pipefailin 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
- A Linux server has high CPU usage. How do you find the cause?
- What do top, htop, vmstat, iostat, ss and lsof each tell you?
- How do you troubleshoot DNS resolution and network connectivity on Linux?
- A server keeps running out of memory and the kernel kills processes. How do you investigate?
- The disk is full, but du shows far less usage than df. What's going on?
- How do systemd units work, and how do you debug a service that won't start?
- Explain Linux file permissions, ownership and the special bits.
- What is load average, and how is it different from CPU utilisation?