Reputation: 1871
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
Upvotes: 0
Views: 1038
Reputation: 12393
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
Upvotes: 1
Reputation: 531325
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
Upvotes: 1
Reputation: 12877
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"
Upvotes: 1