Search code examples
bashcomparison-operators

Bash Script "integer expression expected" , use of floats in bash instead of other language


I am new to bash scripting. My code is :

MK=M
SM=1.4

if [[ $MK == "M" ]]
 then
        if [ $SM -gt 1.3 ]
            then
            echo "Greater than 1.3M"
            else
            echo "Less than 1.3M"
            fi
 else
 echo "Not yet M...."
fi

Reply:

/tmp/tmp.sh: line 6: [: 1.4: integer expression expected
Less than 1.3M

What am i doing wrong ?


Solution

  • It's ultimately because bash is not terribly patient when it comes to floating point numbers. In very simple terms here, I would suggest you do one of two things:

    1. It looks like you are trying to determine if something is larger than 1.3 Mb or not, is this correct? If this is the case, then leave everything the way you have it, and just use Kb for $sm and the compare

      like this:

      #/bin/bash
      
      mk="p"  
      km="p"  
      sm="1400"  
      ms="1300"  
      
      if [[ $mk == $km ]]  
      then  
      if [ $sm > $ms ]  
      then  
      echo "Greater than 1.3M"  
      else  
      echo "Less than 1.3M"  
      fi  
      else  
      echo "Not yet M...."  
      fi
      

      or

    2. Use bc for the calculation of the floating point numbers...

      # /bin/bash
      
      mk="p"
      km="p"
      sm="1.4"
      ms="1.3"
      
      if [ $(echo "$mk == $km" | bc) ]
      then   
      if [ $(echo "$sm > $ms" | bc) ]
      then
      echo "Greater than 1.3M"
      else
      echo "Less than 1.3M"
      fi
      else
      echo "Not yet M...."
      fi
      

    One more thing to note here, is that, as you can see from my code, I have primed new variables with the data, rather than using raw letters and numbers in boolean and compare operations, which can have some genuinely unexpected results. Also, while they may work in some conditions, temporarily, bash prefers all variable names to be in lower-case. Let me know if you have any questions.. However, I have tested both code chunks, and they both work fine.