CPU Usage Threshold Monitor & Automated Process Triage
#!/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"
fiProduction 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
