Saturday, October 8, 2022

[SOLVED] Compare floating point numbers using regex in Bash

Issue

I need to check if current NTP offset is biger than 2.xxxxx , where xxx is any number for example 2.005596757,2.006086349

offset=$(ntpdate -q 1.2.3.4 | head -1 | cut -d " " -f 6 | sed "s/.$//")
echo $offset

current offset variable is: 0.841816 so need to compare if X.XXXXXX is bigger or equal to 2.XXXXXXXXX , where X is any number in range [0-9]

offset=$(ntpdate -q 10.160.82.10 | head -1 | cut -d " " -f 6 | sed "s/.$//")

        
     if [ $offset -ge ([2]+\.?[0-9]*) ]
      then
       echo "offset too high"
     fi

But getting error

./1.sh: line 9: syntax error near unexpected token `('
./1.sh: line 9: `if [ $offset -ge ([2]+\.?[0-9]*)|([0-9]*\.[0-9]+) ]'

Solution

Why don't you compare only the integer part? Like:

if [ ${offset%.*} -ge 2 ]; then
  echo offset too high
fi


Answered By - oguz ismail
Answer Checked By - David Goodson (WPSolving Volunteer)