#!/bin/sh # grab previous stats cache="/tmp/cpuload" [ ! -f "$cache" ] || touch "$cache" # get the currents cpu stats variables curr_stats=$(head -n 1 /proc/stat) prev_stats=$(cat "$cache") # get the stats curr_idle=$(echo "$curr_stats" | awk ' { print $5 } ') prev_idle=$(echo "$prev_stats" | awk ' { print $5 } ') curr_sum=$(echo "$curr_stats" | awk '{ print ($2+$3+$4+$5+$6+$7+$8+$9+$10) }') prev_sum=$(cat "$cache" | awk '{ print ($2+$3+$4+$5+$6+$7+$8+$9+$10) }') if [ -n "$prev_sum" ] ; then # get the delta by subtracting the the current total from the previous total delta=$(($curr_sum - $prev_sum)) # calculate idle delta idle=$(($curr_idle - $prev_idle)) # caclulate working time used=$(($delta - $idle)) # caculate usage cpu_usage=$((100 * $used / $delta)) echo "$cpu_usage%" fi echo "$curr_stats" > "$cache"