我是 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 条件始终产生不正确的输出。
@Ankit:尝试:将
if [ $cpu_usage > $cpu_threshold ]
更改为 if [[ $cpu_usage > $cpu_threshold ]]
用它来比较两个浮点数
$cpu_usage'>'$cpu_threshold | bc -l
这是我的问题的正确且完整的答案。
#! /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