0

I want to store each output of commands mpstat or mpstat -P ALL, like %usr,%nice,%sys,... in a variable.

Can you help me to do this,because I want to sum some of them.

1 Answer 1

1

Its a tough one but still I am managed to get something for you.

This line will print CPU data in a variable named CPU

eval "$(mpstat | awk '{print $3}' | xargs | awk '{print $2"="$3}')"

after doing this execute echo $CPU

you will get

[root@localhost BASH]# echo $CPU
all
[root@localhost BASH]#

and for %usr you can use eval "$(mpstat | awk '{print $4}' | xargs | awk '{print "USR="$3}')"

look at below example

[root@localhost BASH]# eval "$(mpstat | awk '{print $4}' | xargs | awk '{print "USR="$3}')"
[root@localhost BASH]# echo $USR
0.11
[root@localhost BASH]#

I hope you understand how to do this and you can develop complete code for what you want.

Summary:

[root@localhost BASH]# cat  forsome.sh
#!/bin/bash
eval "$(mpstat | awk '{print $3}' | xargs | awk '{print $2"="$3}')"
eval "$(mpstat | awk '{print $4}' | xargs | awk '{print "USR="$3}')"
echo "Number of CPU's :"$CPU
echo "%usr value      :"$USR

[root@localhost BASH]# ./forsome.sh
Number of CPU's :all
%usr value      :0.11
[root@localhost BASH]#
3
  • Thanks dear friend How about %nice,%sys,...can I do something like this to store %nice for example in another variable? nice=$("$(mpstat | awk '{print $4}' | xargs | awk '{print "NICE="$3}')") and sys=$("$(mpstat | awk '{print $4}' | xargs | awk '{print "SYS="$3}')") Dec 26, 2015 at 14:16
  • and show the result of two sys and nice with echo inside the shell like this echo "%nice"$nice and show result of sys, echo "%sys"$sys, is the correct? Dec 26, 2015 at 14:23
  • To develop remaining part of the script you should learn awk. So you will understand what need to be done.
    – Raja G
    Dec 26, 2015 at 15:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .