Mar
14
If you’re a command line freak, you’ve probably use expr for common math calculations but did you know that the bc command allows you to do similar math calculations and is more powerful when it comes to bigger calculations?
bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming language. A standard math library is available by command line option. If requested, the math library is defined before processing any files. bc starts by processing code from all the files listed on the command line in the order listed. After all files have been processed, bc reads from the standard input. All code is executed as it is read. (If a file contains a command to halt the processor, bc will never read from the standard input.)
If the above man page description don’t make any sense yet, then just remember that bc is a command line calculator. The nice thing about bc is that it accepts inputs from files, from standard output and this allows the command line user to pipe data out for quick calculations. The syntax for basic calculation is very similar to Google’s calculator.
Here are some basic examples:
$ cat file.txt
5+5
$ bc < file.txt
10
$ echo 2+2 | bc
4
It’s possible to use basic math with variables:
$ A=9
$ B=6
$ C=$ ((A+B))
$ echo $C
15
Some more basic examples of addition, subtraction, multiplication and division:
$ echo ‘50+20′ | bc
70
$ echo ‘50-20′ | bc
30
$ echo ‘50*20′ | bc
1000
$ echo ‘50/20′ | bc
2
There is a variable called scale and using it adds number of digits which follow the decimal point. By default scale is 0. So the above example shows 2 but if scale variable was used, the result could be displayed in x # of digits.
$ echo ’scale=1;50/20′ | bc
2.5
How about square root, and power:
$ echo ’scale=15;sqrt(8)’ | bc
2.828427124746190
$ echo ‘4^4′ | bc
256
Convert from decimal to hexadecimal, from decimal to binary and from binary back to decimal:
$ echo ‘obase=16;255′ | bc
FF
$ echo ‘obase=2;22′ | bc
10110
$ echo ‘ibase=2;obase=A;10110′ | bc
22
bc in interactive mode:
$ bc
4*4
16
13*13
169
scale=10
199/3
66.3333333333
2^32
4294967296
As you can see, it’s not shy about displaying the big value results. Here are some more resources to help you explore bc further:
- command-line calculations using bc
- Hexadecimal or Binary Conversion
- bc Command
- bc - The shell maestro’s calculator
- bc — The Linux Command-line Calculator
- man bc






