Search code examples
linuxbashfloating-pointcompare

While comparing two integers, if condition does not work correctly in bash script


I am new to bash scripting and am working on a script to calculate CPU usage. Currently, I am calculating the CPU usage and comparing it with a predefined threshold value. However, my if condition always seems to be evaluating as false. I would appreciate assistance in correcting my script.

#!/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

Please review the bash script above, as I've attempted various approaches, but the if condition consistently produces incorrect output.


Solution

  • @Ankit: Try: changing if [ $cpu_usage > $cpu_threshold ] to if [[ $cpu_usage > $cpu_threshold ]]