Skip to content

Instantly share code, notes, and snippets.

@gsingh93
Created December 13, 2014 23:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsingh93/6f68148f984ba42623a8 to your computer and use it in GitHub Desktop.
Save gsingh93/6f68148f984ba42623a8 to your computer and use it in GitHub Desktop.
A script to log cpu usage, memory usage, and temperature usage
#!/bin/bash
# A script to log cpu usage, memory usage, and temperature usage
# TODO:
#
# Log temp awk is not portable
# Validate interval
#
########## Variable Declarations ##########
append=false
output=false
interval=5
########## Function Declarations ##########
parse_options() {
while getopts "t:ai:oh" opt; do
case $opt in
t)
type=$OPTARG
;;
a)
append=true
;;
i)
interval=$OPTARG
if [[ 1 -ne 1 ]]; then
error "Invalid interval"
fi
;;
o)
output=true
;;
h)
display_help
exit 0
;;
\?)
display_help
exit 1
;;
esac
done
}
display_help() {
cat <<EOF
Usage: loghw -t <log_type> [options]
-h display help
-i <arg> Set interval to <arg>
-o Print output to stdout as well as log
-a Append to previous log
The log type is either cpu, mem, or temp.
Logging CPU usage depends on the mpstat package and
logging the temerature depends on the lm-sensors package.
EOF
}
output() {
if $output; then
echo -e "$1" | tee -a $LOG_FILE
else
echo -e "$1" >> $LOG_FILE
fi
}
check_if_installed() {
dpkg -s $1 > /dev/null
return $?
}
error() {
echo -e "\nError: $1. Exiting.";
display_help
exit 1
}
########## START SCRIPT ##########
parse_options "$@"
if [[ -z "$type" ]]; then
error "No log type supplied"
fi
HEADER="Logging started at `date` with interval $interval\n"
if [[ "$type" == "cpu" ]]; then
installed=$(check_if_installed "sysstat")
if [[ "$installed" -eq 1 ]]; then
error "The package sysstat is required to log CPU usage"
fi
LOG_FILE=cpulog
COMMAND="mpstat | awk '/all/ {print 100-\$12}'"
HEADER+="AVG CPU USAGE"
elif [[ "$type" == "mem" ]]; then
LOG_FILE=memlog
COMMAND='free -m | awk '\''/-/ {printf "%s\t%s\n", $3, $4}'\'
HEADER+="USED\tFREE"
elif [[ "$type" == "temp" ]]; then
installed=$(check_if_installed "lm-sensors")
if [[ "$installed" -eq 1 ]]; then
error "The package lm-sensors is required to log CPU temp"
fi
LOG_FILE=templog
COMMAND="sensors | awk '/temp1/ {print \$2}' | head -1"
HEADER+="TEMP"
else
error "Invalid log type"
fi
if ! $append; then
:>$LOG_FILE
fi
output "$HEADER"
while true; do
result="$(eval $COMMAND)"
output "$result"
sleep $interval
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment