How to pass results of bc to a variable

I'm writing a script and I would like to pass the results from bc into a variable. I've declared 2 variables (var1 and var2) and have given them values. In my script I want to pass the results from bc into another variable say var3 so that I can work with var3 for other calculations. So far I have been able write the result to a file which is not what I'm looking for and also I've been able to echo the result in the terminal but I just want to pass the result to a variable at moment so that I can work with that variable.

echo "scale=2;$var1/var2" | bc

Solution 1:

If you're using bash, you'd better use an here string instead of a pipe as in:

bc <<< "scale=2;$var1/$var2"

This will save you a subshell.

Then, to store the output of a command, use a command substitution:

answer=$(bc <<< "scale=2;$var1/$var2")

Edit.

If you want something even cooler than bc, here's dc (reverse polish calculator):

answer=$(dc <<< "2k $var1 $var2/p")

Solution 2:

Command substitution stores the output of a command into a variable.

var3=$(echo "scale=2;$var1/$var2" | bc)