'How to compare floating numbers in bash linux? [duplicate]
I'd like to use if-elif-elif-else-fi to determine a based on the range of t:
a=1000 # t=2-9.5
a=2000 # t=10-14.5
a=4000 # t=15-16.5
a=6000 # t=17-20
My bash file looks like:
t=(2 3 3.5 4 4.5 5 5.5 6 6.5 7 7.5 8 8.5 9 9.5 10 10.5 11 11.5 12 12.5 13 13.5 14 14.5 15 15.5 16 16.5 17 17.5 18 19 20)
len=${#t[*]}
for i in `seq 0 $((len-1))`
do
if [ $(echo "${t[i]} < 10" | bc -l) -eq 1 ];then
a=1000
elif [[ "${t[i]}" -ge '10' && "${t[i]}" -lt '15' ]];then
a=2000
elif [[ "${t[i]}" -ge '15' && "${t[i]}" -lt '17' ]];then
a=4000
else
a=6000
fi
done
And I receive error "syntax error: invalid arithmetic operator (error token is ".5")".
It seems that I don't correctly compare the floating number with integer number. Can anyone help me to solve this problem? Thanks!
Solution 1:[1]
When dealing with floating point numbers we mostly use bc or/and awk.
Suggesting an awk solution:
#!/bin/bash
arr=(2 3 3.5 4 4.5 5 5.5 6 6.5 7 7.5 8 8.5 9 9.5 10 10.5 11 11.5 12 12.5 13 13.5 14 14.5 15 15.5 16 16.5 17 17.5 18 19 20)
for elm in ${arr[@]}; do
a=$(echo ""| awk -v inp="$elm" '
inp >= 2 && inp <= 9.5 {print 1000}
inp >= 10 && inp <= 14.5 {print 2000}
inp >= 15 && inp <= 16.5 {print 4000}
inp >= 17 && inp <= 20 {print 6000}
')
printf "elm=%f\ta=%d\n" $elm $a # debug trace
done
Output:
elm=2.000000 a=1000
elm=3.000000 a=1000
elm=3.500000 a=1000
elm=4.000000 a=1000
elm=4.500000 a=1000
elm=5.000000 a=1000
elm=5.500000 a=1000
elm=6.000000 a=1000
elm=6.500000 a=1000
elm=7.000000 a=1000
elm=7.500000 a=1000
elm=8.000000 a=1000
elm=8.500000 a=1000
elm=9.000000 a=1000
elm=9.500000 a=1000
elm=10.000000 a=2000
elm=10.500000 a=2000
elm=11.000000 a=2000
elm=11.500000 a=2000
elm=12.000000 a=2000
elm=12.500000 a=2000
elm=13.000000 a=2000
elm=13.500000 a=2000
elm=14.000000 a=2000
elm=14.500000 a=2000
elm=15.000000 a=4000
elm=15.500000 a=4000
elm=16.000000 a=4000
elm=16.500000 a=4000
elm=17.000000 a=6000
elm=17.500000 a=6000
elm=18.000000 a=6000
elm=19.000000 a=6000
elm=20.000000 a=6000
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dudi Boy |
