5

How can I obtain CPU percentage usare and RAM percentage printed out in one line on linux? (Using cli)

I have to pass these output string to an LCD display.

Thx a lot

3

Use AWK to Parse Output from Top

top -bn1 | awk '/Mem/ { mem = "Memory in Use: " $5 / $3 * 100 "%" };
                /Cpu/ { cpu = "CPU in Use: " 100 - $8 "%" };
                END   { print mem ", " cpu }'

This will use top's batch mode to print statistics once, which you can then parse any way you like with awk. For example, the code above yielded this in my test:

Memory in Use: 93.866%, CPU in Use: 1.7%

Obviously, your output will vary. You can also adjust the output format if you need more (or less) information.

2

You can parse the output of some of the Unix utilities, such as vmstat:

$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 1  0  75812 282632 115704 891332    0    1    22    54  138  362 15  2 80  2
$ vmstat | sed -n '3s/ \+/\t/gp' | cut -f5,14
280904  15

The above prints the free memory and the CPU usage.

If you want used memory, you can use another utility, such as top in batch mode, as suggested by CodeGnome and by me in an earlier answer.

$ top -bn1 | sed -rn '3s/[^0-9]* ([0-9\.]+) .*/\1/p;4s/.*,  ([0-9]+) .*/\1/p' | tr '\n' ' '
10.4 3787340

Or to get percentages, you can do

$ top -bn1 | \
> sed -rn '3s/[^0-9]* ([0-9\.]+) .*/\1/p;4s/[^0-9]*([0-9]+)[^0-9]+([0-9]+) .*/\1 \2/p' | \
> { read cpu; read tot used; echo $cpu $(( 100*used/tot )); }
10.3 94

I'm sure there are more elegant solutions though.

2
  • The OP asked for percentages. – terdon Jun 2 '13 at 17:26
  • @terdon You're right, thanks, I was looking at the title. Updated – Lev Levitsky Jun 2 '13 at 18:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.