Reputation: 3
Script:
echo $1 $n
while true
do
ps -aux | awk '{print $1 "\t" $3 "\t" $4 "\t" $11}' > task.log
while IFS=' ' read r
do
echo $r
done < task.log | grep "$n" | awk '/a/{sum+=$1} END{print"Total CPU Usage:", sum}' >> monitor2.log
sleep $1
done
This is a simple script to see the cpu usage by output -aux result in task.log and let grep and awk process it sum it all by entering a keyword
The problem is that the result is always when I run ./monitor1.sh 2 firefox
Total CPU Usage: 0
I tested if I put grep replace $n with firefox and not variable, the output is
Total CPU Usage: 1.1
Upvotes: 0
Views: 97
Reputation: 140970
In your script:
n=$2
or just use $2
positional variable insteadtee
to pipe to itps -axu
and then limiting columns with awk
looks strange. ps
can format the output by itselfps | grep
is bad, use pgrep
for thatYour script after some fixing may look like this:
while true; do
cpuusage=$(
pgrep "$2" |
tee >(xargs ps -aux >task.log) |
xargs ps -o cpu% |
awk '{sum += $1} END {print sum}'
)
echo "Total CPU Usage: $cpuusage" >> monitor2.log
sleep "$1"
done
ps -aux | grep ...
xargs
passes pgrep
outupt to ps -o %cpu=
ps -o %cpu=
prints percent cpu usage for each processawk
is used to sum it.monitor2.log
file.Upvotes: 1
Reputation: 2724
I guess you're after something like this:
ps aux | awk '$11 ~ /firefox/{ sum += $3 } END { print sum }'
The awk
checks field 11 of every row produced by ps
and if it contains firefox
, it executes the associated {}
block. Beware, on different systems the ps
outputs are different.
You want to run this within a watch
command. Eg. like this (notice how you can avoid quoting hell with the use of awk variables).
ps-sum() { ps aux | awk -v regex=$1 '$11 ~ regex { sum += $3 } END { print sum }' ;}
export -f ps-sum
watch -x bash -c "ps-sum firefox"
Upvotes: 0