≡ Menu

Unix bc Command Line Calculator in Batch Mode

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
Add your comment

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

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.

  • dj November 18, 2009, 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

  • balmar November 18, 2009, 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.

  • Paul Reiber November 18, 2009, 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

  • William Heiland March 7, 2014, 2:59 pm

    I want to export a variable in bc calculator like you do in bash. Can you please show me how in an e-mail.