1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Discuss in my forum

How to Use the "bc" Calculator in Scripts

By

See More About

The Linux program bc can be used as a convenient desktop calculator. For interactive use you simply type "bc" at the command prompt in a terminal window and start typing arithmetic expressions.

When performing a series of calculations repeatedly it makes sense to use the bc calculator as part of a script. The simplest form of such a script would look something like this:

   #!/bin/bash
   echo '6.5 / 2.7' | bc

The first line is just the path the executable that runs this script. The second line contains two commands. The echo command generates a string containing the mathematical expression contained in single quotes. The pipe operator '|' passes this string as argument to the bc program. The output of the bc program is than display on the command line (stdout).

In order to execute this script you open a terminal window and navigate to the directory where the script located. Let's assume the script file is called "bc_script.sh. Make sure the file is executable using the chmod command:

   chmod 755 bc_script.sh

Then you would enter:

   ./bc_script.sh

The result will be the following output:

   2

In order to show 3 decimal digits you would a "scale" statement inside the string delimited by the single quotes as in this example:

   #!/bin/bash
   echo 'scale=3; 6.5/2.7' | bc

For better readability the line with the calculations can be rewritten on multiple lines:

   echo 'scale=3; 
            6.5/2.7' | bc

In order the break the command line into multiple lines you can put a backslash at the end of the line:

     echo 'scale=3; 
              var1 = 6.5 / 2.7;
              var1 ' \
           | bc

In order to include command line arguments in your bc calculations you have change the single quotes into double quotes so that the command line parameter symbols are interpreted by the Bash shell. For example:

    echo "scale=3; 
             var1 = 6.5 / 2.7;
             var2 = 14 * var1;
             var2 *= $1;
             var2 " \
          | bc

The first command line argument is accessed using the variable "$1", the second argument is accessed with "$2", etc.

Now you can write your own customized arithmetic functions in separate Bash scripts and call them from other scripts.

Besides the bc utility, the Bash shell provides a few other methods for <a href="http://linux.about.com/od/Bash_Scripting_Solutions/a/Arithmetic-In-Bash.htm">performing arithmetic operations</a>.

 

  1. About.com
  2. Technology
  3. Linux

©2014 About.com. All rights reserved.