Interview Prep/Shell Scripting/Scenarios: health checks, monitoring and alerts

A dashboard reads a JSON status file that your script writes every minute. Sometimes the dashboard shows parse errors. Fix it.

IntermediateScenarioScenarios: health checks, monitoring and alerts
Answer

Situation read → The dashboard reads the file while the script is in the middle of writing it.

What I'd do →

out=/var/lib/opskit/status.json
tmp=$(mktemp "${out}.XXXXXX")
jq -n --arg host "$(hostname -s)" --argjson disk "$disk_pct" --arg ts "$(date -u +%FT%TZ)" \
  '{host: $host, disk_pct: $disk, updated: $ts}' > "$tmp"
chmod 0644 "$tmp"
mv -f -- "$tmp" "$out"
  1. Write to a temp file in the same directory, then rename.
  2. Build JSON with jq so it is always valid.

Why → Rename is atomic on the same filesystem; readers see the old or new file, never a partial one.

Interview tip → Explain that mktemp creates files with mode 0600, so set permissions before the mv if others must read it.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: health checks, monitoring and alerts