0

I'm using an array to try to subtraction. However, when my script just gives me the total of my array with a negative sign in front of it. Any suggestions?

elif [ "$OP" = "Subtraction" ]; then
    echo "Please enter the number of values you would like to perform $OP"
    read num
        while [[ $num -gt $i ]]; do
            echo "Enter your value"
            read value
            let total=$total-$value
            let valuearr[$i]=$value
            let i=$i+1
        done
        echo "You entered ${valuearr[*]}, and asked me to perform $OP. The answer is $total."
  • What is the exact output that you get from this script fragment? If total is unset, you will get a negative sum if you enter positive values. – Kusalananda Aug 2 '16 at 22:11
  • $total starts empty, so when you enter 1, 2, and 3, your script computes 0 - 1 - 2 - 3, which clearly is the same as -(1 + 2 + 3). – choroba Aug 2 '16 at 22:12
  • 1
    What is the value of $i when this script fragment is entered? What about $total? – roaima Aug 2 '16 at 22:23
2

If I set i=1 and total=0 before hand and change the test to -ge then it seems to work:

OP=Subtraction
if [ "$OP" = "Subtraction" ]; then
    echo "Please enter the number of values you would like to perform $OP"
    read num
    i=1
    total=0
        while [[ $num -ge $i ]]; do
            echo "Enter your value"
            read value
            let total=$total-$value
            let valuearr[$i]=$value
            let i=$i+1
        done
        echo "You entered ${valuearr[*]}, and asked me to perform $OP. The answer is $total."
fi

$ bash x
Please enter the number of values you would like to perform Subtraction
3
Enter your value
1
Enter your value
2
Enter your value
4
You entered 1 2 4, and asked me to perform Subtraction. The answer is -7.

By not setting i=1 you'll miss one element of the ${valuearr[*]} output. total=0 is just good code, in case the variable was used elsewhere.

Clearly 0-1-2-4 == -7 and so the result is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.