0

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!

markp-fuso
  • 28,790
  • 4
  • 16
  • 36
WUYing
  • 71
  • 5
  • 2
    In the `if` block, `bc -l` approach is used. Why isn't it used in the two `elif` blocks as well? Is that by design? – user10304260 Apr 23 '22 at 16:08
  • turn on debugging (`set -xv`) and run your script again; you'll find the first error message is generated for the tests `[[ 17.5 -ge 10 ]]` and `[[ 17.5 -ge 15 ]]`; which appears to be related to @stackinside's comment/question re: why you aren't using `bc -l` for all 5 tests (assuming you need to keep using `bc -l` as opposed to some other tool, eg, `awk`, `perl`, `php`, etc) – markp-fuso Apr 23 '22 at 16:15

1 Answers1

0

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
Dudi Boy
  • 4,551
  • 1
  • 15
  • 30