比较两个整数时,if 条件在 bash 脚本中无法正常工作

问题描述 投票:0回答:3

我是 bash 脚本新手,正在编写一个脚本来计算 CPU 使用率。目前,我正在计算 CPU 使用率并将其与预定义的阈值进行比较。然而,我的 if 条件似乎总是被评估为 false。我希望能帮助纠正我的脚本。

#!/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 脚本,因为我尝试了各种方法,但 if 条件始终产生不正确的输出。

linux bash floating-point compare
3个回答
3
投票

@Ankit:尝试:将

if [ $cpu_usage > $cpu_threshold ]
更改为
if [[ $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
© www.soinside.com 2019 - 2024. All rights reserved.