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
  • 129,424
  • 31
  • 207
  • 592
Judy
  • 1,595
  • 6
  • 19
  • 41

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
  • 12,320
  • 2
  • 11
  • 18
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
  • 497,756
  • 71
  • 530
  • 681
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
  • 367,544
  • 15
  • 269
  • 518
Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38