Unix bc Command Line Calculator in Batch Mode

by Ramesh Natarajan on November 18, 2009

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
Download Free eBook - Linux 101 Hacks

Get free Unix tutorials, tips and tricks straight to your email in-box.

If you enjoyed this article, you might also like..

  1. How To Install, Edit, or Remove Cron Jobs in Batch Mode
  2. How To Execute SSH and SCP in Batch Mode (Only when Passwordless login is enabled)
  3. How To Capture Unix Top Command Output to a File in Readable Format
  4. Do You Like to Perform Vi Style Editing in BASH Command Line ?
  5. Command Line Tricks: How To Identify Date and Time of a Unix Command Execution
  

Vim 101 Hacks Book

{ 1 trackback }

Destillat KW47-2009 | duetsch.info - GNU/Linux, Open Source, Softwareentwicklung, Selbstmanagement, Vim ...
November 20, 2009 at 3:47 am

{ 3 comments… read them below or add one }

1 dj November 18, 2009 at 12:22 pm

Dave Taylor had an article in Linux Journal on this topic:

Work the Shell – Solve: a Command-Line Calculator
http://www.linuxjournal.com/article/9891

2 balmar November 18, 2009 at 1:31 pm

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.

3 Paul Reiber November 18, 2009 at 5:25 pm

Hi, Ramesh!

There are a couple of useful other ways to use bc that you didn’t mention.

The first is using “HERE files”. For example:

$ bc < < HERE
> 1+3
> last/2
> HERE
4
2
$

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
5

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!
-Paul

Leave a Comment

Previous post:

Next post: