2017-02-28 52 views
-1

我是bash脚本的新手。我正在编写一个脚本来计算CPU使用率。所以我在做的是计算CPU使用率,并与预定义的值即阈值进行比较。但我的条件总是出错。请帮我纠正我的剧本。比较两个数字,但如果条件无法正常工作

#!/bin/bash 
#checking the cpu usage 
cpu_usage=$(mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12 }') 
cpu_threshold=1.00 
if [ $cpu_usage > $cpu_threshold ] ; then 
echo "The CPU utilization is above threshold : $cpu_usage %" 
else 
echo "The CPU utilization is below threshold : $cpu_usage %" 
fi 

请在bash做检查上面的脚本东阳我已经尝试了许多方法,但始终如果条件是给错误的输出。

回答

2

@Ankit:尝试:改变if [ $cpu_usage > $cpu_threshold ]if [[ $cpu_usage > $cpu_threshold ]]

+0

谢谢你的回答。 –

+2

我在想浮点运算在Bash中不起作用 - 现在我意识到,虽然算术运算可能不会,但比较起作用。请参阅:http://stackoverflow.com/questions/12722095/how-do-i-use-floating-point-division-in-bash – codeforester

+0

@ RavinderSingh13你可以帮助我与'和'运营商枯萎其他条件相同的上述问题相同的类型。就像[$ cpu_usage> $ cpu_threshold]和[[$ cpu_usage> $ cpu_threshold]]是否正确一样 –

0

利用这个来比较两个浮点数

$cpu_usage'>'$cpu_threshold | bc -l 
0

这里是我的问题的正确和完整的答案。

#! /bin/bash 
    #checking the cpu usage 
    cpu_usage=$(mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12 }') 
    cpu_threshold=70 
    echo $cpu_usage 
    echo $cpu_threshold 
    if [[ $cpu_usage > $cpu_threshold ]] ; then 
    echo "The CPU utilization is above threshold : $cpu_usage %" 
    else 
    echo "The CPU utilization is below threshold : $cpu_usage %" 
    fi