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:
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:
The result will be the following output:
In order to show 3 decimal digits you would a "scale" statement inside the string delimited by the single quotes as in this example:
echo 'scale=3; 6.5/2.7' | bc
For better readability the line with the calculations can be rewritten on multiple lines:
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:
var1 = 6.5 / 2.7;
var1 ' \
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:
var1 = 6.5 / 2.7;
var2 = 14 * var1;
var2 *= $1;
var2 " \
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>.