0

my task is to verify if $VAL NUMBER could be float or integer , is less then number 1

I did

val=0.999
[[ $val -lt 1 ]] && echo less then 1
-bash: [[: 0.999: syntax error: invalid arithmetic operator (error token is ".999")

what is the right way to compare any $val number ( float or integer ) and test it if the value is less than 1?

solutions can be also with Perl/Python line linear that will be part of my bash script

brian d foy
  • 124,803
  • 31
  • 200
  • 568
Judy
  • 1,285
  • 4
  • 14
  • 34

3 Answers3

1

Using awk:

awk -v val=$val 'val < 1 { print "less that 1" }' <<< /dev/null

Pass the variable $val to awk with -v and then when it is less than 1, print "less than 1"

Raman Sailopal
  • 11,713
  • 2
  • 8
  • 16
1

Use bc. Write the expression you want to evaluate to bc's standard input, and it will output the result. In this case, a boolean expression will produce 0 if false, 1 if true.

if [[ $(echo "$val < 1" | bc) == 1 ]]; then
    echo less than 1
fi
chepner
  • 446,329
  • 63
  • 468
  • 610
1

Since shell itself cannot perform operations on floating numbers bc is commonly used for this purpose. In your case, it would be:

#!/usr/bin/env bash

val=0.999
if [ "$(bc <<< "$val < 1")" -eq 1 ]
then
    echo less than 1
fi

And since you specifically asked about Perl/Python this is how you would do that in Python:

#!/usr/bin/env bash

val=0.999
if [ "$(python3 -c "print(1) if $val < 1 else print(0)")" -eq 1 ]
then
    echo less than 1
fi

And finally, Perl:

#!/usr/bin/env bash

val=0.999
if perl -e'exit $ARGV[0] < 1' "$val"
then
    echo less than 1
fi
ikegami
  • 343,984
  • 15
  • 249
  • 495
Arkadiusz Drabczyk
  • 10,250
  • 2
  • 20
  • 35