bc command in Linux

March 4, 2022

bc command in Linux is actually a calculator "language". It comes preinstalled with Linux. Like bash and zsh, you can use it in interactive mode (i.e. type bc in your terminal, hit Enter button, put your equations and get your answers) as well as in shell scripts.

Some people like to call it the "Basic Calculator" and discard it altogether. But I call it the "Best Calculator" because it provides advanced facilities as well - It has for and while loops, and if-else statements, among others with syntax similar to the C programming language.

Here, in this article, I will touch upon its basic applications and how I use it in the shell scripts and in its interactive mode.

Why bc is the best calculator in Linux

  • Many of you prefer "modern" Graphical User Interface (GUI) based calculators to bc - One of the reasons is its default "ugly" look. Another reason is that every time you enter into bc, you need to set a scale for total number of decimal digits printed after the decimal point. But, for me, they are not the problems. You can very easily set an alias for both removing the warranty warnings as well as setting the scale. I will talk about this in the upcoming paras.

Figure: "ugly" bc

Figure: "ugly" bc

  • Another feature of the bc is its usage of space - less RAM, less Hard Disk, less screen space given lack of buttons etc.

  • At the same time for the calculation history - you don't have to scroll much.

  • All the terminal's shortcut keys are available - scroll up/down, copy and paste, etc. Similarly, if you use vim keys in your terminal (for example I use vim keys in my URxvt, and alacritty), that will be available as well.

  • Terminal themes - colorscheme, pywal, etc. - are automatically get available.

  • It even supports comparision and boolean operators, functions such as read similar to that in the C language. So you can exploit your talent in that regard as well and do complex calculations.

  • You can enhance its features by writing your own functions such as differentiation and integration functions, factorial(x), etc. in files and load them at the start of the bc. It is described below in one of the headings.

  • Quiet Versatile - you can use it not only interactively but also in scripts which the GUI based calculator can't.

Fig: the above i3bar uses paste -sd '+' "$rxdeltafile" | bc

Fig: the above i3bar uses paste -sd '+' "$rxdeltafile" | bc

  • In bash or zsh, you can use their Arithmatic Evaluation functionality i.e. ((expression)). But in strictly POSIX compliant shells such as dash, there is nothing like ((expression)) and hence, you don't have any option other than the bc.

  • On top of that, bash shell does not even provide floating point calculations (ex - echo $((5+5.1)) throws error in bash) . So in this case, bc is a life saver.

How to use bc command interactively

To enter into bc's interactive mode, simply use the command bc in your terminal.

[ajay@lenovo ~]$ bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.

You can also force the bc command into the interactive mode using the flag -i or --interactive.

Quit: To quit from the bc's interactive mode, use the command quit, or shortcut key ctrl + \ (the SIGQUIT), or ctrl + c (the SIGINT) or ctrl + d.

How to set the scale (outputs in decimal point) in bc

By default, bc sets the scale to 0. That means - zero number of digits will be printed out after the decimal point. In other words, only the integer part is printed. To set it to some non-zero value use scale=n as shown below:

[ajay@lenovo ~]$ bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
scale=3
5/4
1.250

Variables and values in bc

This is one of the features not available in GUI-based calculators. You can assign any value to any variable.

For the following example, I am assigning value 3 to a variable var. Now, you can use this value in the future!!! Then the print command prints any variable's value.

[ajay@lenovo ~]$ bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
var=3
var1=var*2
print var1
6

Previous answer in bc using the "last" variable

The last variable is a predefined variable and it contains the last answer. Using this, you can concatenate your answers and solve a long equation. Without the last variable, you will need to constantly copy and paste the answers. For example, to solve 3+8789/3*6*9 step by step:

[ajay@lenovo ~]$ bc
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
scale=10
8789/3
2929.6666666666
last*6
17577.9999999996
last*9
158201.9999999964
3+last
158204.9999999964

How to remove the warranty and other information from the bc command in Linux

To remove all kinds of information from bc, you need to use the --quiet or -q flag.

[ajay@lenovo ~]$ bc --quiet
scale=3
5/4
1.250

How to use the bc command in Linux to convert a number from one base to another

bc command has ibase and obase variables for input and output bases respectively.

For example, to find the decimal number corresponding to hexadecimal number 'E', you need to define obase as 10 and ibase as 16.

[ajay@lenovo ~]$ bc --quiet
obase=10
ibase=16
E
14

⚠️ Be Careful: if you set ibase first and then obase, you will get unexpected answers:

[ajay@lenovo ~]$ bc --quiet
ibase=16
obase=10
E
E

The reason is that the first line's ibase=16 asks the bc to treat all the upcoming numbers as hexadecimal numbers. Therefore, the 10 in the next line obase=10 becomes 16. Hence, the second line gets transformed into obase=16. And that's why E is printed as E.

Trigonometric, logarithmic, and exponential functions in bc command in Linux

To use these functions, you need to load the math library using the flag --mathlib or -l. Here is a list of available functions in the math library and their descriptions:

  • s(x) is sine(x) where x is in radians; similarly, c(x) is cosine(x).

  • a(y) is tan-1(y) and the answer will be in radians.

  • l(x) is loge(x) i.e. ln(x).

  • e(x) is ex.

  • Bessel function j(n,x)

At the same time, it also sets the default scale to 20 as you can in the following example:

[ajay@lenovo ~]$ bc --quiet --mathlib
pi=4*a(1)
s(pi)
.00000000000000000002

Advanced bc commands in Linux

Similar to C language, bc has its own conditional statements (if-else), loops (for and while), break and continue, return, comparison operators (>=, <=, <, >, ==, !=), boolean operators (!, ||, &&), ++var, var++, --var, var--, read, return and other functions.

Please look at the man page to know more.

Executing bc command on a file containing all the equations

You can put all the commands, which you are going to type in the interactive mode, into a file and then execute the bc command on that file.

[ajay@lenovo ~]$ bc FILE

Now, the bc will first execute all lines one by one starting from the beginning in the FILE. After executing these lines, bc will read from the standard input. If there is no standard input, bc will enter into the interactive mode.

Example:

[ajay@lenovo ~]$ cat equation.txt
print "remainder of 5/4 is "
5%4
/* this is a comment */
last+2

[ajay@lenovo ~]$ bc equation.txt 
bc 1.07.1
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006, 2008, 2012-2017 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
remainder of 5/4 is 1
3
^C
(interrupt) Exiting bc.

[ajay@lenovo ~]$ echo 'print "standard input\n"' | bc equation.txt
remainder of 5/4 is 1
3
standard input

[ajay@lenovo ~]$

📝 Note 1: As you can see in the above example, /* */ is used for comment, and % is used for the remainder.

📝 Note 2: ^C is ctrl+c I pressed to exit from the interactive mode.

📝 Note 3: You can also use multiple files containing your bc-commands.

[ajay@lenovo ~]$ bc FILE1 FILE2

📝 Note 4: Use the command quit at the end of the FILE to prevent bc from entering into the interactive mode.

👨‍🔧 Application: Some of you complain that the GUI-based calculators have extra facilities which are not available in bc like unit and currency conversions. In bc, you can easily add new functionalities by loading FILE(s) at the start. For example, to create a factorial function (n!), create a file factorial.bc with the following contents in it:

define f (x) {
                if (x <= 1) return (1);
                return (f(x-1) * x);
              }

Now, 5! gives 5*4*3*2*1=120 as given below:

[ajay@lenovo ~]$ bc --quiet factorial.bc 
f(5)
120

How to use bc command in shell scripts

In order to use bc in shell scripts, just pipe all the commands, which you would have typed in its interactive mode, into the bc.

Learn here about what is a shell script and how to create one.

For instance, using the echo command, I will be executing the following command:-

[ajay@lenovo ~]$ echo 'scale=3; 5/4' | bc
1.250

Fun Point 😃: The above behavior is just like that in bluetoothctl - you can either put your Bluetooth commands directly into the interactive-bluetoothctl or pipe them into the bluetoothctl using echo. This is what I love about Linux. There are many features that are the same across a wide variety of tools and commands.

Creating bc alias to set the scale and remove the warranty information

Put the following alias in your shell configuration file (.bashrc and .zshrc for bash and zsh respectively):

alias bc='bc --quiet <(echo "scale=5;print\"scale=5\n\"")'

📖 Explanation:

  • The above alias prints "scale=5" into the bc's interactive mode just to remind you that scale=5 has been set and you don't have to set it again.

  • <(command) in bash or zsh is called Process Substitution. It is used to simulate a file. The command's output becomes the content of the file.

Now, the command bc will start with no information and it will set the scale automatically for you. Similarly, you can also put other bc commands in the alias.

Fig: bc command in Linux before setting the alias

Fig: bc command in Linux before setting the alias

Fig: bc command in Linux after setting the alias

Fig: bc command in Linux after setting the alias

Conclusion

That was just the tip of the iceberg. For me, it is the Best Calculator instead of the Basic Calculator. What is it for you or did you just dismiss it out of the hand due to paucity of time - write it in the comment section.

Thanks for reading. If you have any suggestions/problems, please put a comment for them as well.