A small sh script to record process RAM and CPU usage… here is a solution to the problem.
A small sh script to record process RAM and CPU usage
I have the following sh script on my centos machine:
echo "PID,CPU,MEM,PROC"
while [ 1 ]
do
ps aux | grep mysql | awk '{print $2",", $3",", $4",", $11}'
sleep 1
done
The output of each loop has this output:
1163, 0.0, 0.0, /bin/sh
1265, 0.0, 1.5, /usr/libexec/mysqld
11807, 0.0, 0.3, grep
I would like to know how to loop through the output and use variables to combine values and return only one line: PID and PROC are not needed in the combined result
mysql, 0.0, 1.8
where 0.0 is CPU (sum of all process
CPU usage) and 1.8 RAM (sum of all process RAM usage).
Solution
ps -eo "comm %cpu %mem" --no-headers | awk '{a[$1] = $1; b[$1] += $2; c[$1] += $3}END{for (i in a)printf "%s, %0.1f, %0.1f\n", a[i], b[i], c[i]}' | sort
Sample output:
awk, 0.0, 0.0
bash, 0.0, 1.5
ps, 0.0, 0.0
sort, 0.0, 0.0
Specific process:
ps -C bash -o "comm %cpu %mem" --no-headers | awk '{a[$1] = $1; b[$1] += $2; c[$1] += $3}END{for (i in a)printf "%s, %0.1f, %0.1f\n", a[i], b[i], c[i]}'
Output:
bash, 0.0, 1.5