Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 使用shell脚本比较cpuusage值_Linux_Shell_Unix_Command - Fatal编程技术网

Linux 使用shell脚本比较cpuusage值

Linux 使用shell脚本比较cpuusage值,linux,shell,unix,command,Linux,Shell,Unix,Command,如何使用shell脚本计算CPU使用率值,如果[$message-ne”“],我会在第行中得到一个错误[:=:预期的一元运算符] #!/bin/sh expected_cpuusage="95" cpu_usage=`top -n 1 -b|grep Cpu|awk '{print $2}'|cut -d"%" -f1""` message="" if [ $cpu_usage -gt $expected_cpuusage ] ##{x%?}

如何使用shell脚本计算CPU使用率值,如果[$message-ne”“],我会在第
行中得到一个错误[:=:预期的一元运算符]

   #!/bin/sh

    expected_cpuusage="95"
    cpu_usage=`top -n 1 -b|grep Cpu|awk '{print $2}'|cut -d"%" -f1""`
    message=""
    if [ $cpu_usage -gt $expected_cpuusage ]    ##{x%?}
    then
       echo "CPU usage exceeded";
       if [ $message -ne "" ]
       then
         message="$message\n\nCPU usage exceeded configured usage limit \nCurrent CPU usage is $cpu_usage\nConfigured CPU usage is $expected_cpuusage";
       else
         message="CPU usage exceeded configured usage limit \nCurrent CPU usage is $cpu_usage\nConfigured CPU usage is $expected_cpuusage";
       fi ;
    fi

是重定向操作符。您需要
-gt

if [ $cpu_usage -gt $expected_cpuusage ]
这要求$cpu_usage看起来像一个整数,如果不是,则会失败并生成错误。(即,如果它包含0-9以外的字符,-gt不比较浮点值,因此包含“.”的字符串将不起作用。)对于浮点比较,请使用expr:

if expr $cpu_usage \> $expected_cpuusage > /dev/null; then 
有更巧妙的方法可以使用bash内置的[[]进行比较,但是这些构造限制了脚本的可移植性。 使用空字符串时会出现另一个错误。请尝试使用引号:

if [ "$message" -ne "" ]
但使用起来要清楚得多:

if [ -n "$message" ]
:

否则,空字符串将弄乱表达式

更好的是:

if [ -n "$message" ]

还是同一个错误,我也为if条件更改了我的问题。更改后,我还得到了预期的整数表达式。基本问题仍然是缺少引号,如l0b0的回答中所述。@triplee,没有。基本问题最初是他使用了>而不是-gt。当问题被编辑为使用-gt时,th基本问题变成了试图使用test来比较浮点值。缺少引号是次要的。这个问题询问的是
-ne
,没有迹象表明它被编辑过。解析
top
的输出几乎不是正确的方法。尝试
人工正常运行时间
,或者直接从
/proc
读取,如果你我们的体系结构就是这样。我同意@tripleee。这里有一个更好的方法来获得CPU利用率:
b这种方法的一个好处是,您可以删除
scale=3;
,并确保您现在得到一个非浮点数,您可以直接使用
-gt
if [ -n "$message" ]