bc is a calculator scripting language. Scripts in bc can be executed with the bc command. Imagine a test.bc file contains the following code:
scale = 2; (10.0*2+2)/7;
That means you can run bc like this:
$ cat test.bc | bc 3.14
bc can do far more than just divide two numbers. It’s a fully-fledged scripting language on its own and you can do arbitrarily complex things with a bc script. A bc script might be the ending point of a pipeline of data, where the data files are initially massaged into a stream of data rows, and then a bc script is used to compute the values we’re looking for.
You can omit the copyright messages displayed while running bc using the “-q” option with it.
$ bc –q 2 + 2 4 quit
The ability to take standard input means we can use documents, strings, and pipes to pass scripts. This is a here string example:
$ bc <<< "2+2" 4
If you get an error as shown below while executing the bc command:
bc: command not found
you may try installing the bc package as shown below as per your choice of distribution.
Distribution | Command |
---|---|
OS X | brew install bc |
Debian | apt-get install bc |
Ubuntu | apt-get install bc |
Alpine | apk add bc |
Arch Linux | pacman -S bc |
Kali Linux | apt-get install bc |
CentOS | yum install bc |
Fedora | dnf install bc |
Raspbian | apt-get install bc |
The bash calculator recognizes these:
- Numbers (both integer and floating point)
- Variables (both simple variables and arrays)
- Comments (lines starting with a pound sign or the C language /* */ pair)
- Expressions
- Programming statements (such as if-then statements)
- Functions