命令顶部-b -n 1 | grep Cpu总是返回相同的值

时间:2015-09-23 11:07:45

标签: linux shell grep

当我运行命令top -b -n 1| grep Cpu时,它总是返回相同的值:

Cpu(s): 0.3%us, 0.3%sy, 0.0%ni, 99.4%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st

但是当我删除-n 1部分时,结果以

开头
Cpu(s): 0.3%us, 0.3%sy, 0.0%ni, 99.4%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st 

然后后续值不同。

有什么理由吗?我怎样才能获得不同的价值?

2 个答案:

答案 0 :(得分:2)

检查您的top手册页:

   The top command calculates Cpu(s) by looking at  the  change  in
   CPU  time  values between samples. When you first run it, it has
   no previous sample to compare to, so these  initial  values  are
   the percentages since boot. It means you need at least two loops
   or you have to ignore summary output from the first loop.   This
   is  problem  for  example  for  batch  mode. There is a possible
   workaround if you define the CPULOOP=1 environment variable. The
   top  command  will  be  run  one  extra hidden loop for CPU data
   before standard output.

答案 1 :(得分:1)

您定义选项-n max将允许顶部执行max次迭代。如果您提供1,则只能从1次迭代中获取数据。当然还要获得单行数据。

我不知道你是如何使用输出的。 top -b -n x|grep Cpu可以提供不同的输出,具体取决于top的版本。在我的Archlinux上,top -b -n 1 |grep Cpu的输出是:

kent$ (master|…) top -b -n 1 |grep Cpu
%Cpu0  :  12.7/4.1    17[|||||||||||                                                    ]
%Cpu1  :  69.9/17.3   87[|||||||||||||||||||||||||||||||||||||||||||||||||||||||        ]
%Cpu2  :  69.0/19.2   88[|||||||||||||||||||||||||||||||||||||||||||||||||||||||        ]
%Cpu3  :  68.1/18.0   86[||||||||||||||||||||||||||||||||||||||||||||||||||||||         ]