Nice script :-)
getstat is a bit odd:
- It runs a
grepand then ased, when probably a singlesed(orawk) could do the job - It replaces spaces with
x, but not very clear why:- I see that
extractusesxas the separator, but it could just as well use space for that - I also see that using
xas the separator makes thechangefunction slightly simpler, because it lets you writeextract $ENDSTATinstead ofextract "$ENDSTAT", but then again, thathaving to quote doesn't seem a big problem
- I see that
In extract, you run an echo and then a cut:
echo $1 | cut -d 'x' -f $2
In bash you can use here stringshere strings, which is better than using echo:
cut -d 'x' -f $2 <<< $1
But actually, if we keep the spaces as the separator in getstat, then we can rewrite both of these functions with fewer extra processes:
function getstat() {
sed -ne '/^cpu */s/^cpu *//p' /proc/stat
# that is:
# -n to not print lines by default
# for lines matching /^cpu */, delete /^cpu */, and print the line
}
function extract() {
# example 1st param: "437797 1219 185341 549955584 58662 4 7083 0 0 0"
# example 2nd param: 1, 2, 3, ... (the n-th column to use)
n=$2 # saving the position param
set -- $1 # reset positional params from $1, so that $1=437797, $2=1219, ...
echo ${!n} # echo the n-th positional param
}
function change() {
local e=$(extract "$ENDSTAT" $1)
local b=$(extract "$STARTSTAT" $1)
echo $(( $e - $b ))
}