Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Use GNU bc (Basic Calculator) in Linux?
GNU bc (Basic Calculator) is a powerful command-line calculator utility in Linux that enables users to perform advanced mathematical calculations, including floating-point arithmetic, complex mathematical functions, and programmable calculations. It supports arbitrary precision arithmetic, making it ideal for both simple calculations and complex mathematical operations.
Installing GNU bc
Most Linux distributions include GNU bc in their default repositories. First, check if bc is already installed on your system
$ bc --version
If bc is not installed, use your distribution's package manager to install it
Ubuntu/Debian-based systems:
$ sudo apt-get install bc
Fedora/CentOS/RHEL systems:
$ sudo dnf install bc
Arch Linux systems:
$ sudo pacman -S bc
After installation, verify bc is working by starting the interactive calculator
$ bc
Basic Arithmetic Operations
GNU bc supports standard arithmetic operations with proper order of operations (PEMDAS). You can use bc interactively or pass expressions directly from the command line.
Interactive Mode Examples
Addition:
$ bc 2 + 3
5
Subtraction:
5 - 3
2
Multiplication:
2 * 3
6
Division:
6 / 3
2
Command Line Usage
You can also perform calculations directly from the command line using echo and pipes
$ echo "2 + 3" | bc
5
Advanced Mathematical Operations
GNU bc supports advanced mathematical functions and operations for scientific calculations.
Exponentiation and Modulus
Exponentiation (power):
2^3
8
Modulus (remainder):
10 % 3
1
Mathematical Functions
For advanced functions, you need to load the math library using the -l option
$ bc -l
Square root:
sqrt(25)
5
Natural logarithm:
l(10)
2.30258509299404568401
Sine function (radians):
s(1.5708)
1.00000000000000000000
Setting Precision and Scale
GNU bc allows you to control the precision of calculations using the scale variable
$ bc scale=2 10/3
3.33
scale=5 10/3
3.33333
Variables and Programming Features
GNU bc supports variables, functions, and control structures for complex calculations
$ bc x = 5 y = 3 x * y + 2
17
Useful Command Options
| Option | Description |
|---|---|
| -l | Load math library (sine, cosine, logarithm functions) |
| -i | Force interactive mode |
| -q | Quiet mode (suppress welcome message) |
| -s | Process exactly POSIX bc language |
Conclusion
GNU bc is a versatile command-line calculator that provides both basic and advanced mathematical capabilities in Linux. With support for arbitrary precision arithmetic, mathematical functions, variables, and programming constructs, bc serves as an excellent tool for quick calculations and complex mathematical operations in shell scripts and interactive use.
