thank you
thank you

Reputation: 21

bash scripting if statement, comparing decimal

Kind of new to bash scripting and is having trouble with the below code. I am trying to compare the array number with the number you have input from the "read ans" the problem is mostly comparing decimal numbers

    BGpercent=(0 99 99.3 99.6 99.8 100)
    BGpoint=(0 1 2 3 4 5) 
    read ans
    for (( c=${#BGpercent[@]}; c>=0; c-- ))
    do  
       echo "${BGpercent[$c]}"
        if [ "${BGpercent[$c]}" <= "$ans"  ];  
        then
        result=${BGpoint[$c]}
        break
        fi
    done
    echo $result | bc -lstrong text

Error - ./testscript.sh: =: No such file or directory

Upvotes: 2

Views: 382

Answers (2)

thank you
thank you

Reputation: 21

BGpercent=(0 99 99.3 99.6 99.8 100) BGpoint=(0 1 2 3 4 5)

echo " Write in your number:" read number

for (( c=${#BGpercent[@]}-1; c>-1; c-- )) do echo ${BGpercent[$c]} bool=echo "if (${BGpercent[$c]} <= ${number}) 1" | bc if [ "$bool"1 -eq 11 ] ; then result=${BGpoint[$c]} break fi

Upvotes: 0

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

I guess the problem is in your if check (floating point comparison).

#!/bin/bash

    BGpercent=(0 99 99.3 99.6 99.8 100)
    BGpoint=(0 1 2 3 4 5)
    read ans
    for (( c=$[ ${#BGpercent[@]} - 1 ] ; c>=0; c-- ))
    do
        if (( $(echo "${BGpercent[$c]} <= $ans" |bc -l) ));
        then
        result=${BGpoint[$c]}
        break
        fi
    done

Also, the variable c value must be decremented in the beginning, else it will contain an invalid index value. I am not sure what you intent to do with the last line (echo $result | bc -lstrong text)

Upvotes: 1

Related Questions