How to do simple Arithmetic on Linux Terminal?

While some GUI based Linux desktops give a calculator to be used in a similar way to what is available in Windows, the terminal has lot of features to do both simple and advanced level arithmetic calculations. In this article we will see how we can invoke various calculations from the Linux terminal itself

Using bc

The command bc stands for basic calculator. Using it we can do various operations like arithmetic calculations, assigning values to variables, using comparison or relational operators and using many math functions available through bc itself. Also it has features for conditional statements and iterative statements. Below will see some examples.

Typing directly into bc

In this case the results are printed just below where you enter 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'.

After Running the above code the command prompt returns.

bc With echo

We can type in the Calculation and pipeline the result to bc command. It will give the result at the command Prompt Itself.

~$ echo '3/15' | bc
~$ echo '3+15' | bc
~$ echo '(13-5)%2' | bc
# Logical comparison
~$ echo '45 < 20 ' | bc
# Applying length function
~$ echo 'length(4578.62)' | bc

Using expr

Using expr is another way to perform calculations at the terminal itself. Like bc you you have to write your calculation as an expression. But in this case you begin it with expr. Below are some examples.

# Logical comparison
# Using \ as escape character
~$ expr 55 \> 5
~$ expr 55 \< 5
# Using with shell variables
~$ a = 234
~$ b = 6
~$ c = `expr $a / $b`
~$ echo $c

Using Shell Variables

Using the shell variables we can also perform certain calculations. Only single operations are carried out in one step and the result is fed into another variable which can be used in the next step. Please note the space between numeric values and the operator signs.

~$ var1 = $((3 * 12))
~$ var2 = $(($var1 - 4 ))
~$ echo $var2

Updated on: 03-Jan-2020


Kickstart Your Career

Get certified by completing the course

Get Started