Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comparison of integer and floating point numbers in shell script

Tags:

linux

shell

unix

In shell script how can we compare (integer and floating point) ,(flaoting point and floating point),(floating point and integer),(integer and integer) with only one if condition.

i have few examples like

 set X=3.1
  set Y=4.1
  if [ $X < $Y ] then
    echo "wassup"
  endif

But running the above from cron job doesnt seem to work.

like image 900
Rajeev Avatar asked Dec 01 '22 23:12

Rajeev


1 Answers

The way to carry out floating point operations in bash is to use bc which is available on almost all linux distributions.

# bc will return 0 for false and 1 for true
if [ $(echo "23.3 > 7.3" | bc) -ne 0 ] 
then 
  echo "wassup"
fi

There's a good article available on linux journal about floating point math in bash using bc.

like image 111
brice Avatar answered Dec 15 '22 13:12

brice