Skip to Content
Linux Shell Scripting Cookbook - Third Edition
book

Linux Shell Scripting Cookbook - Third Edition

by Clif Flynt, Sarath Lakshman, Shantanu Tushar
May 2017
Beginner
552 pages
28h 47m
English
Packt Publishing
Content preview from Linux Shell Scripting Cookbook - Third Edition

How to do it...

This shell script monitors and calculates CPU usages for one hour:

#!/bin/bash
#Name: pcpu_usage.sh
#Description: Script to calculate cpu usage by processes for 1 hour

#Change the SECS to total seconds to monitor CPU usage.
#UNIT_TIME is the interval in seconds between each sampling

SECS=3600
UNIT_TIME=60

STEPS=$(( $SECS / $UNIT_TIME ))

echo Watching CPU usage... ;

# Collect data in temp file

for((i=0;i<STEPS;i++))
do
  ps -eocomm,pcpu | egrep -v '(0.0)|(%CPU)' >> /tmp/cpu_usage.$$
  sleep $UNIT_TIME
done

# Process collected data
echo
echo CPU eaters :

cat /tmp/cpu_usage.$$ | \
awk '
{ process[$1]+=$2; }
END{ 
  for(i in process)
  {
    printf("%-20s %s\n",i, process[i]) ;
  }

   }' | sort -nrk 2 | head

#Remove the temporary log file ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering Linux Shell Scripting - Second Edition

Mastering Linux Shell Scripting - Second Edition

Mokhtar Ebrahim, Andrew Mallett

Publisher Resources

ISBN: 9781785881985