You may be using bc command in command line for calculations. It can also be used for batch mode calculations as explained below.
1. Calculation using Single command
$ echo "4+10" | bc 14
2. Calculation using Multiple commands
$ echo "obase=15;5+9" | bc E
3. Using previous results in the current operation
In the following example, “last” represents the result of the previous calculation.
echo "1+3;last/2" | bc 4 2
In the following example, . (dot) represents the result of the previous calculation.
$ echo "1+3;./2" | bc 4 2
4. Another way of executing bc calculation
bc <<< 4+2 6
Comments on this entry are closed.
Dave Taylor had an article in Linux Journal on this topic:
Work the Shell – Solve: a Command-Line Calculator
Thanks Ramesh. Do you know calc at
http://www.isthe.com/chongo/tech/comp/calc/ ? (And I also have one in my mobile: http://midp-calc.sourceforge.net/Calc.html ) I love them both.
There are a couple of useful other ways to use bc that you didn’t mention.
The first is using “HERE files”. For example:
in this case, the > (and $ of course) are prompts from the interactive shell. However, the same thing works within a shell script. Shell variable expansion will apply to the content in the HERE file, so this can very powerful; the HERE file content doesn’t have to be static. Note that both numbers AND operators for bc can be represented in variables.
The second useful way to use bc is the backtick operator. AKA ‘results of’.
$ x=`echo 4+1|bc`
$ echo $x
This is kind of like ‘eval’ but it’s eval-ing a bc expression rather than a shell expression. Again, a pretty powerful construct.
Thanks for the ongoing stream of great geek stuff!
I want to export a variable in bc calculator like you do in bash. Can you please show me how in an e-mail.