Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a non-integer number with if in bash [duplicate]

Tags:

linux

bash

ubuntu

i try to validate if a number with decimals is between in a specify range, i mean like the following example :

rangeA=58.5
rangeB=61.5
number=62.7

 if [[ ( "$number" > "$rangeA" | bc ) || ( "$number" = "$rangeA" | bc ) ]] && [[ ( "$number" < "$rangeB" | bc ) || ( "number" = "rangeB" | bc ) ]]; then

but i'm stuck in this operation, I would appreciate your help thanks

like image 432
shaveax Avatar asked Dec 18 '22 22:12

shaveax


2 Answers

Bash's < and > compare strings, -lt and -gt compare integers, the only way to compare floating point numbers is to shell out to bc(1) (which you do, but you do it wrong):

rangeA=58.5
rangeB=61.5
number=62.7

if (( $(bc <<<"$number >= $rangeA && $number <= $rangeB") )); then
    echo yes
else
    echo no
fi

bc prints 1 or 0 to the standard output, and bash's arithmetics context (((expression))) tests it for zero and sets the status code accordingly.

like image 89
eush77 Avatar answered Dec 21 '22 10:12

eush77


You can use awk:

rangeA=58.5
rangeB=61.5
number=62.7

if awk -v number=$number -v rangeA=$rangeA -v rangeB=$rangeB  '
   BEGIN{exit !(number >= rangeA && number <= rangeB)}'
then
   echo "condition matched"
else
   echo "condition didn't match"
fi
like image 20
anubhava Avatar answered Dec 21 '22 11:12

anubhava