Skip to content

Instantly share code, notes, and snippets.

@leandroudala
Created February 9, 2026 15:02
Show Gist options
  • Select an option

  • Save leandroudala/f2e98761877e17f76662ac60238a9732 to your computer and use it in GitHub Desktop.

Select an option

Save leandroudala/f2e98761877e17f76662ac60238a9732 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Configuration
THRESHOLD=90
LOG_FILE="/tmp/cpu_high_usage.log"
while true; do
# Get current CPU idle percentage and calculate usage
# We use 'top' in batch mode to get a reliable snapshot
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
# Check if usage is greater than or equal to threshold
if (( $(echo "$CPU_USAGE >= $THRESHOLD" | bc -l) )); then
echo "--- High CPU Detected: $(date) ---" >> $LOG_FILE
echo "Total CPU Usage: $CPU_USAGE%" >> $LOG_FILE
# Record the top 5 CPU consuming processes
echo "Top Processes:" >> $LOG_FILE
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -n 6 >> $LOG_FILE
echo "-----------------------------------" >> $LOG_FILE
fi
# Wait 5 seconds before checking again
sleep 5
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment