Search code examples
linuxbashubuntuarithmetic-expressions

Adding numbers in bash script says "not found"


I'm making a bash script in Vim editor for my operating systems fundamentals class, and I am having an extremely simple yet frustrating error occur where I cannot add variables together and set the sum to another variable. I've tried numerous formats to get this done, however it either prints out each value or a ": not found" error. Here is the code I have so far, I simply want to set the sum of the values for each test into the variable 'finalgrade' and print the output.

echo "Enter assignment mark (0 to 40): " ; read assignment 
echo "Enter test1 mark (0 to 15): " ; read test1  
echo "Enter test2 mark (0 to 15): " ; read test2  
echo "Enter final exam mark (0 to 30): " ; read exam  
finalgrade = $assignment + $test1 + $test2 + $exam  
echo "Your final grade is : "$finalgrade

This is an example of what I get when I run it:

$ sh myscript
Enter assignment mark (0 to 40):
1
Enter test1 mark (0 to 15):
2
Enter test2 mark (0 to 15):
3
Enter final exam mark (0 to 30):
4
myscript: 5: myscript: finalgrade: not found
Your final grade is :

I instead expected the last line to be:

Your final grade is : 10

Thanks,


Solution

  • This line

    finalgrade = $assignment + $test1 + $test2 + $exam
    

    will not perform any math. Googling "bash math" will provide various ways to do this but here is one;

    finalgrade=$((assignment + test1 + test2 + exam))
    

    It is worth noting that your actual problem is that you have spaces beside the assignment = which causes bash to interpret this as a command "finalgrade" (not found) instead of an assignment. Variable assignments must not have spaces beside the =.