2

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

3
  • chmod 750 testscript.sh then try to launch it. Also, add a shebang. Commented Nov 9, 2016 at 9:04
  • doesn't works, still having the same error Commented Nov 9, 2016 at 9:13
  • This part of the message =: is strange. Commented Nov 9, 2016 at 9:23

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

4 Comments

Hi, thanks for the reply! now i am getting this error. syntax error on line 1, teletype
Did you change the c variable initialization in the for loop as well? See this link: unix.com/shell-programming-and-scripting/…
@A.M.D, did you change this? c=$[ ${#BGpercent[@]} - 1
@Thirupathi Thangavel : Yes i did
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.