Ayush joshi
Ayush joshi

Reputation: 325

How to calculate CPU usage by user (%us) using Bash script

I want to calculate CPU usage by %us for a particular instant, but once I run this:

top -b -d1 -n1|grep -i "Cpu(s)"

I get fair o/p:

Cpu(s): 0.6%us, 0.2%sy, 0.0%ni, 98.9%id, 0.3%wa, 0.0%hi, 0.1%si, 0.0%st

But it seems to be repetitive all the time its not getting updated as per top returns. Kindly give me some tips to update this command so that I can get it to get correct result of CPU usage at a particular instant.

Upvotes: 1

Views: 813

Answers (2)

nervosol
nervosol

Reputation: 1291

Somehow first result of top command is always the same. Second one is correct. Increase -n parameter number to get second one, and get last one using tail

top -bd1n2 | grep Cpu | tail -n 1 | awk '{print $2}'

Upvotes: 1

Jayesh Bhoi
Jayesh Bhoi

Reputation: 25865

Try

top -b -n2 | grep "Cpu(s)"|tail -n 1 | awk '{print $2 + $4}'

Upvotes: 1

Related Questions