mrj9797
mrj9797

Reputation: 51

"Attempted assignment to a non-variable" in bash

I'm new to Bash and I've been having issues with creating a script. What this script does is take numbers and add them to a total. However, I can't get total to work.It constantly claims that total is a non-variable despite it being assigned earlier in the program.

error message (8 is an example number being entered)

./adder: line 16: 0 = 0 + 8: attempted assignment to non-variable (error token is "= 0 + 8")
#!/bin/bash

clear
total=0
count=0


while [[ $choice != 0 ]]; do

    echo Please enter a number or 0 to quit

    read choice

    if [[ $choice != 0 ]];
    then
        $(($total = $total + $choice))

        $(($count = $count + 1))


        echo Total is $total
        echo
        echo Total is derived from $count numbers

    fi

done


exit 0

Upvotes: 1

Views: 4044

Answers (1)

John Kugelman
John Kugelman

Reputation: 361556

Get rid of some of the dollar signs in front of the variable names. They're optional inside of an arithmetic context, which is what ((...)) is. On the left-hand side of an assignment they're not just optional, they're forbidden, because = needs the variable name on the left rather than its value.

Also $((...)) should be plain ((...)) without the leading dollar sign. The dollar sign will capture the result of the expression and try to run it as a command. It'll try to run a command named 0 or 5 or whatever the computed value is.

You can write:

((total = $total + $choice))
((count = $count + 1))

or:

((total = total + choice))
((count = count + 1))

or even:

((total += choice))
((count += 1))

Upvotes: 3

Related Questions