Greg M Greg M - 10 months ago 170
Linux Question

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):
Enter test1 mark (0 to 15):
Enter test2 mark (0 to 15):
Enter final exam mark (0 to 30):
myscript: 5: myscript: finalgrade: not found
Your final grade is :

I instead expected the last line to be:

Your final grade is : 10


Answer Source

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))