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
up vote 21 down vote accepted

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


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

answer=$(dc <<< "2k $var1 $var2/p")
  • 1
    Yes I'm using bash, can you please clarify on the subshell? Is there a disadvantage? – shaolin Dec 15 '12 at 22:16
  • 2
    Each time you use a pipe | the command on the right of the pipe is executed in a subshell, and it takes resources to open a new subshell (it's like opening a new instance of bash to execute that command). If you can avoid it, avoid it. Here, piping an echo to bc will run the command bc in a subshell and is, in some sense, retarded (no offence), since bash has the wonderful here-string construct <<< to avoid stupid things like these. – gniourf_gniourf Dec 15 '12 at 22:19
  • @gniourf_gniourf Then again, if you cared about resource usage, you'd use /bin/sh (dash) instead of bash, but dash doesn't have <<<. – Gilles Dec 15 '12 at 22:33
  • Thank you for the helpful information!! This is good information to know regarding preserving resources and subshells. I greatly appreciate you input. – shaolin Dec 15 '12 at 22:37
  • 1
    @Gilles just compare time for i in {1..10000}; do : <<< ""; done with time for i in {1..10000}; do echo "" | : ; done, you'll see a dramatic difference. Then you're right, a heredoc is slightly faster than a herestring. But it's more awkward to type as a one-liner. – gniourf_gniourf Dec 21 '12 at 7:57

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

var3=$(echo "scale=2;$var1/$var2" | bc)
  • Thank you! This got me exactly where I wanted to be, after probably an hour of researching. Thanks – shaolin Dec 15 '12 at 22:18

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.