#!/bin/bash # Temp file to store previous readings tmpfile="/tmp/cpu_prev_all" # Get all per-core lines mapfile -t cpu_lines < <(grep '^cpu[0-9]' /proc/stat) # On first run, save and exit if [[ ! -f $tmpfile ]]; then printf "%s\n" "${cpu_lines[@]}" > "$tmpfile" echo "..." # No previous data exit 0 fi # Load previous readings mapfile -t prev_lines < "$tmpfile" # Sanity check if (( ${#cpu_lines[@]} != ${#prev_lines[@]} )); then echo "..." # Core count mismatch (e.g., suspend/resume) printf "%s\n" "${cpu_lines[@]}" > "$tmpfile" exit 0 fi total_usage=0 for i in "${!cpu_lines[@]}"; do # Current read -r cpu user nice system idle iowait irq softirq steal _ _ <<< "${cpu_lines[$i]}" total_now=$((user + nice + system + idle + iowait + irq + softirq + steal)) idle_now=$((idle + iowait)) # Previous read -r _ pu pn ps pi piw pir psf pst _ _ <<< "${prev_lines[$i]}" total_prev=$((pu + pn + ps + pi + piw + pir + psf + pst)) idle_prev=$((pi + piw)) # Deltas diff_total=$((total_now - total_prev)) diff_idle=$((idle_now - idle_prev)) if ((diff_total > 0)); then usage=$((100 * (diff_total - diff_idle) / diff_total)) total_usage=$((total_usage + usage)) fi done # Output total usage (per-core sum) #echo '{"usage": ${total_usage}%}'} printf "{ \"text\": %6.0f, \"tooltip\": \"%s\" }" "$total_usage" "test" # Save current readings printf "%s\n" "${cpu_lines[@]}" > "$tmpfile"