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 do simple Arithmetic on Linux Terminal?
While GUI-based Linux desktops provide calculator applications similar to Windows, the Linux terminal offers powerful features for both simple and advanced arithmetic calculations. This article demonstrates how to perform various calculations directly from the Linux terminal.
Using bc (Basic Calculator)
The bc command stands for "basic calculator" and supports arithmetic operations, variables, comparison operators, mathematical functions, conditional statements, and loops. Below are some practical examples ?
Interactive bc Mode
Type bc to enter interactive mode where results appear immediately below your calculations ?
$ bc bc 1.06.95 Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 2+9 11 13%5 3 quit
After running the above code, the command prompt returns.
Using bc with echo
You can pipe calculations to bc using echo for quick one-line operations ?
~$ echo '3/15' | bc 0 ~$ echo '3+15' | bc 18 ~$ echo '(13-5)%2' | bc 0 # Logical comparison ~$ echo '45 < 20' | bc 0 # Applying length function ~$ echo 'length(4578.62)' | bc 6 ~$
Using expr Command
The expr command provides another way to perform calculations at the terminal. You write expressions as command arguments, and it evaluates them ?
# Logical comparison # Using \ as escape character for operators ~$ expr 55 \> 5 1 ~$ expr 55 \< 5 0 # Using with shell variables ~$ a=234 ~$ b=6 ~$ c=`expr $a / $b` ~$ echo $c 39
Using Shell Arithmetic Expansion
Shell variables with arithmetic expansion $(( )) provide a convenient way to perform calculations. Note the proper spacing around operators ?
~$ var1=$((3 * 12)) ~$ var2=$(($var1 - 4)) ~$ echo $var2 32
Comparison of Methods
| Method | Best For | Supports Decimals | Interactive Mode |
|---|---|---|---|
bc |
Complex calculations, functions | Yes | Yes |
expr |
Simple expressions, scripting | No | No |
$(( )) |
Integer math in scripts | No | No |
Conclusion
The Linux terminal provides multiple arithmetic calculation methods. Use bc for advanced math and decimal operations, expr for simple integer expressions, and $(( )) for efficient integer arithmetic in shell scripts.
