OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

bc – An Arbitrary Precision Calculator Language

We have seen how the shell can handle many types of integer arithmetic, but what if we need to perform higher math or even just use floating point numbers? The answer is, we can’t. At least not directly with the shell. To do this, we need to use an external program. There are several approaches we can take. Embedding Perl or AWK programs is one pos- sible solution, but unfortunately, outside the scope of this book.

Another approach is to use a specialized calculator program. One such program found on many Linux systems is called bc.

The bc program reads a file written in its own C-like language and executes it. A bc script may be a separate file or it may be read from standard input. The bc language sup- ports quite a few features including variables, loops, and programmer-defined functions. We won’t cover bc entirely here, just enough to get a taste. bc is well documented by its man page.

Let’s start with a simple example. We’ll write a bc script to add 2 plus 2:


/* A very simple bc script */


2 + 2

/* A very simple bc script */


2 + 2


The first line of the script is a comment. bc uses the same syntax for comments as the C programming language. Comments, which may span multiple lines, begin with /* and end with */.


 

Top OS Cloud Computing at OnWorks: