'Bash average with scale=2

Trying to create a simple calculating the average from say quiz numbers. I do something like this but am getting errors.

echo "Enter your name and 3 quiz scores: "
read name q1 q2 q3

let avg=`echo "scale=2; (q1+q2+q3)/3" | bc`

Lets say the user enters mike 12 14 15. The average return value should be 13.66



Solution 1:[1]

Try

avg=`echo "scale=2; ($q1+$q2+$q3)/3" | bc`

Or, more succinctly (and more efficiently):

avg=`bc <<<"scale=2; ($q1+$q2+$q3)/3"`
  • You were missing $ prefixes for the variable references.
  • let is used for Bash's integer-only arithmetic, so you can't use it assign the output of your bc command - a decimal fraction - to a variable (a decimal fraction such as 13.66 is not a valid arithmetic expression in Bash).
    A normal variable assignment will do.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1