#!/bin/sh # Script to display CPU usage RED="\e[31m" GREEN="\e[32m" YELLOW="\e[33m" CYAN="\e[36m" ENDCOLOR="\e[0m" # Cache in tmpfs to improve speed and reduce SSD load cache=/tmp/cpu-script-cache rm /tmp/cpu-script-cache 2>/dev/null while true; do sleep 1 cpu_stats=$(awk '/^cpu / {print $2 + $3 + $4 + $5, $5}' /proc/stat) if [ ! -f "$cache" ]; then echo -n "  ${CYAN}--%${ENDCOLOR} \r" echo "$cpu_stats" >"$cache" continue fi prev_stats=$(cat "$cache") total=$(echo "$prev_stats" | awk '{print $1}') prev_idle=$(echo "$prev_stats" | awk '{print $2}') curr_total=$(echo "$cpu_stats" | awk '{print $1}') curr_idle=$(echo "$cpu_stats" | awk '{print $2}') total_diff=$((curr_total - total)) idle_diff=$((curr_idle - prev_idle)) if [ "$total_diff" -eq 0 ]; then usage=0 # Avoid division by zero else usage=$((100 * (total_diff - idle_diff) / total_diff)) fi if [ "$usage" -lt 50 ]; then echo -n "  ${GREEN}${usage}%${ENDCOLOR} \r" elif [ "$usage" -lt 70 ]; then echo -n "  ${YELLOW}${usage}%${ENDCOLOR} \r" else echo -n "  ${RED}${usage}%${ENDCOLOR} \r" fi echo "$cpu_stats" >"$cache" done