title: Get CPU usage in bash, without top or sysstat
body: <p>My test script looks like this:</p>
  
  <pre><code>prev_total_cpu=0
  prev_idle_cpu=0
  
  while true
  do
   tempenv=$(grep "cpu " /proc/stat)
   #get cpu times
   read cpu user nice system idle &lt;&lt;&lt; "$tempenv"
  
   #calculate total cpu time
   let total=$[$user + $nice + $system + $idle]
  
   #calculate delta total and delta idle
   prev_total="prev_total_$cpu"
   prev_idle="prev_idle_$cpu"
   let delta_total=$[$total-${!prev_total}]
   let delta_idle=$[$idle-${!prev_idle}]
  
   #calculate cpu usage
   printf "$cpu: $[100*($delta_total-$delta_idle)/$delta_total]%% "
  
   #remember total and idle times
   let prev_total_$cpu="$total"
   let prev_idle_$cpu="$idle"
  
   echo ""
   sleep 1
  done
  </code></pre>
  
  <p>Now, the same thing with multiple CPU support:</p>
  
  <pre><code>prev_total_cpu=0
  prev_idle_cpu=0
  prev_total_cpu0=0
  prev_idle_cpu0=0
  prev_total_cpu1=0
  prev_idle_cpu1=0
  
  while true
  do
   #loop through cpus
   grep "cpu" /proc/stat | while IFS='\n' read tempenv
   do
    #get cpu times
    read cpu user nice system idle &lt;&lt;&lt; "$tempenv"
  
    #calculate total cpu time
    let total=$[$user + $nice + $system + $idle]
  
    #calculate delta total and delta idle
    prev_total="prev_total_$cpu"
    prev_idle="prev_idle_$cpu"
    let delta_total=$[$total-${!prev_total}]
    let delta_idle=$[$idle-${!prev_idle}]
  
    #calculate cpu usage
    printf "$cpu: $[100*($delta_total-$delta_idle)/$delta_total]%% "
  
    #remember total and idle times
    let prev_total_$cpu="$total"
    let prev_idle_$cpu="$idle"
   done
   echo ""
   sleep 1
  done
  </code></pre>
  
  <p>Doesn't work - it shows the same numbers over and over again. What am I doing wrong?</p>
  
  <p>Sub-question:</p>
  
  <p>I would like to initialize <code>prev_total_$cpu</code>and <code>prev_idle_$cpu</code> in a loop, but I don't know how to set the condition. I need the opposite of <code>sed -ne 's/^cpu\(.*\) .*/\1/p' /proc/stat</code> so I can loop through its output and do the initialization.</p>