Using bc command In Linux With Examples: Basic Calculator

bc command in Linux basically stands for Basic Calculator or command line calculator that can be used for doing various basic mathematical calculations. Since the mathematical operations are very common in every programming language, the Linux or Unix operating system also offers the bc (and expr command) command to do such arithmetic operations. Also, these commands can be used in bash or shell script to evaluate mathematical expressions.

Syntax to use bc command in Linux

bc [ -hlwsqv ] [long-options] [ file_name]

Installing bc on a Linux machine

If you notice your system have no bc installed, then you can achieve this by getting through below mentioned commands for different Linux distros:

For Ubuntu/Debian

sudo apt install bc

For CentOS/RHEL

sudo yum install bc

for Fedora

sudo dnf install bc

Running these commands, you can easily install bc on your machine, while in order to open this basic calculator on your machine, type the following command.

bc

bc command in linux

Running this command will open an interactive interface on screen and you can start doing arithmetic operations.

Options available to use with bc (Basic Calculator) in Linux

-h | –help: Displays the help information and exits
-i | –interactive: Enforce the bc to run in interactive mode
-l | –mathlib: Defines the standard math library
-w | –warn: Throws warnings for extensions to POSIX bc
-s | –standard: Used for processing exactly the POSIX bc language
-q | –quiet: Used for printing not the normal GNU bc welcome message
-v | –version: Displays the version details and exits

About features that bc command supports in Linux with examples:

1: Arithmetic operators

echo “15+20” | bc
17

2: Increment/Decrement operators

echo “var=12;++var” | bc
13
echo “var=13;--var” | bc
12

3: Assignment operators

echo “var=20;var” | bc
20

4: Comparison or Relational operators

echo "7>3" | bc
1

echo "10==4" | bc
0

Note: 1 indicates the expression is true while 0 indicates the expression is false.

5: Logical or Boolean operators

echo "10 && 5" | bc
1

6: Math functions

The bc supports various mathematical functions which includes:

s (x): The sine of x, where x is in radians
c (x): The cosine of x where xyz is in radians
a (x): The arctangent of x, arctangent returns radians

and so on.

7: Conditional statements

echo 'x=10;y=8;if(n>m) print "x is greater" else print "y is greater" ' | bc -l
x is greater

8: Iterative statements

echo "for(i=10; i>=1; i--) {i;}" | bc
10
9
8
7
6
5
4
3
2
1