I'm writing a script to monitor CPU and MEMORY utilization during stability test and in the end I want to present it in a graph or another visual tool. to do so I'm trying to extract %CPU and %MEM from top command by column name
##to get indexes of columns I need
indexCPU=$(top -b -n 1 | grep PID | tr -s ' ' '\n' | nl -nln | grep "%CPU" | cut -f1)
infexMEM=$(top -b -n 1 | grep PID | tr -s ' ' '\n' | nl -nln | grep "%MEM" | cut -f1)
## get values from top in a while loop
while [ $UPTIME -lt $DURRATION ]; do
scpu=$(top -b -n 1| grep -w squeezer | tr -s ' ' | cut -d ' ' -f $indexCPU )
smem=$(top -b -n 1| grep -w squeezer | tr -s ' ' | cut -d ' ' -f $infexMEM )
echo "$scpu $smem" >> stabilityTestUsageM.txt
sleep 300
done
now when I do this sometimes it gets the right value but in other, I get the values to the left
for example, I got the output
S
for this:
top -b -n 1| grep -w squeezer | tr -s ' ' | cut -d ' ' -f $indexCPU
while this is the result for top -b -n 1| grep -w squeezer:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
8048 root 20 0 1953716 442376 8460 S 0.0 2.7 0:30.97 squeezer
Do you have an idea of what's wrong?
Thanks