132

I am looking for a calculator which can do calculations in the terminal itself, without any other extra prefixes and suffixes.

For example: If I typed something like 10000-9000 in the terminal, the answer should come out as 1000.

Once again I am saying, I just need a quick calculator in the terminal, without any characters added. I know if I switch to Python, it can do that, but I don't want it in such a way.

Raja G
  • 105,327
  • 107
  • 262
  • 331

25 Answers25

104

You can use calc. Is not installed by default, but you can install it quickly using the following command:

sudo apt-get install apcalc

After you have installed, you can do any calculation do you wish:

$ calc 5+2
    7
$ calc 5-2
    3
$ calc 5*2          
    10
$ calc 5/2
    2.5
$ calc 5^2
    25
$ calc 'sqrt(2)' 
    1.4142135623730950488
$ calc 'sin(2)'
    0.9092974268256816954
$ calc 'cos(2)'
    -0.416146836547142387
$ calc 'log(2)'
    ~0.30102999566398119521
$ calc 'sqrt(sin(cos(log(2))))^2'
    ~0.81633199125847958126
$ # and so on...

For more information , view its man-page

Raja G
  • 105,327
  • 107
  • 262
  • 331
Radu Rădeanu
  • 174,089
  • 51
  • 332
  • 407
100

You can do simple integer arithmetic natively in bash using the ((...)) syntax, e.g.

$ echo $((10000-9000))
1000

There is also the bc calculator, which can accept arithmetic expressions on standard input

$ echo "10000-9000" | bc
1000

The bc program can do floating point arithmetic as well

$ echo "scale = 3; 0.1-0.09" | bc
.01
steeldriver
  • 142,475
90

Bash Arithmetic

Another possible solution is to add a simple function for Bash's built-in arithmetic. Put this in your .bashrc file to try it out:

=() {
    echo "$(($@))"
}

So now, you don't even need $((...)) anymore, just = which seems natural enough.

Replacement

Another thing if you want to be even faster: you can make it replace p with + and x with *. This will work for that:

=() {
    local IFS=' '
    local calc="${*//p/+}"
    calc="${calc//x/*}"
    echo "$(($calc))"
}

= 5 x 5 # Returns 25 = 50p25 # Returns 75

Now you don't even need Shift anymore, the only thing is in front of arithmetic.

Hexadecimal output

Output can be displayed in both decimal and hexadecimal, if so desired. (Note: using x substitution will conflict with the 0x... hex syntax)

=() {
    local answer="$(($@))"
    printf '%d (%#x)\n' "$answer" "$answer"
}

Example:

$ = 16 + 0x10
272 (0x110)

$ = 163 + 164 69632 (0x11000)

Using bc

If you want slightly more advanced calculations, you can pipe it to bc like so:

=() {
    local IFS=' '
    local calc="${*//p/+}"
    calc="${calc//x/*}"
    bc -l <<<"scale=10;$calc"
}

= 'sqrt(2)' # Returns 1.4142135623 = '4*a(1)' # Returns pi (3.1415926532)

The functions provided by bc are as follows (and can be found in man bc):

sqrt ( expression )
       The value of the sqrt function is the square root of the expression.  
       If the expression is negative, a run time error is generated.

s (x) The sine of x, x is in radians.

c (x) The cosine of x, x is in radians.

a (x) The arctangent of x, arctangent returns radians.

l (x) The natural logarithm of x.

e (x) The exponential function of raising e to the value x.

j (n,x) The Bessel function of integer order n of x.

It also supports if, for, while, and variables like a programming language. Though it may be better to write to a file if you wanted that.

Keep in mind that it will substitute p and x in function/variable names. It may be better to just remove the replacements.

Using gcalccmd

You can also make the function call gcalccmd (from gnome-calculator) like so:

=() {
    local IFS=' '
    local calc="$*"
    # Uncomment the below for (p → +) and (x → *)
    #calc="${calc//p/+}"
    #calc="${calc//x/*}"
    printf '%s\n quit' "$calc" | gcalccmd | sed 's:^> ::g'
}

= 'sqrt(2)' # Returns 1.4142135623 = '4^4' # Returns 256

The available functions seem to be (taken straight from the source code), == denotes equivalent functions:

ln()
sqrt()
abs()
int()
frac()
sin()
cos()
tan()
sin⁻¹() == asin()
cos⁻¹() == acos()
tan⁻¹() == atan()
sinh()
cosh()
tanh()
sinh⁻¹() == asinh()
cosh⁻¹() == acosh()
tanh⁻¹() == atanh()
ones()
twos()
kiri
  • 28,986
30

Unfortunately, there's no "easier" way to do this. The interactive python interface on the command line is the best suited for what you need, because unlike apcalc\, python is included in Ubuntu. I am not sure if bc is included still, however, python is the hands-down favorite for this stuff.

You can just run the interactive python interface on the command line, and then do math that way. You can use that as your calculator.

To do that, you open the terminal, type python, then hit the Enter button.

Then, in the python prompt that shows up, you can type your math in. For example, 10000 - 9000. The next line output is the result.


If you mean, though, something where you just load the terminal and can do this...

$ 10000 - 9000
1000
$

... then no there's no way to do this in just the terminal without anything else, because Bash doesn't handle numerical arguments like that.

Thomas Ward
  • 78,878
24

I'd advise you to create a simple function for basic Python calculations. Something like this in your .bashrc:

calc() {
    python3 -c 'import sys; print(eval(" ".join(sys.argv[1:])))' "$@"
}

calc 5 + 5
# Returns 10

result="$(calc 5+5)"
# Stores the result into a variable

If you want to do more advanced math, you can use the following one which imports all of the math module's functions. (see here for more info)

calc() {
    python3 -c 'from math import *; import sys; print(eval(" ".join(sys.argv[1:])))' "$@"
}

calc 'sqrt(2)'  # Needs quotes because (...) is special in Bash
# Returns 1.4142135623730951

result="$(calc 'sqrt(2)')"
# Stores the result into a variable

(Note: Because Python is a programming language, some things may seems strange, e.g. ** for powers of and % for modulo)

Alternatively you can create a Python script calc,

#!/usr/bin/python3
from math import *
import sys
print(eval(' '.join(sys.argv[1:])))

place it in a directory included in the PATH variable and set its executable flag to get the same calc command as above (no need to create a Bash function to run a Python script).

If you want a method in pure Bash, use steeldriver's answer. This answer is only really beneficial if you need the more advanced functions (i.e. from math), as Python is relatively slow compared to Bash.


I'm not sure if this breaks your "switch to python it can do that & I don’t want it in such a way." note, but you don't need to enter the interactive prompt and the result is accessible in Bash so this answer seems valid (to me, at least).

David Foerster
  • 36,890
  • 56
  • 97
  • 151
kiri
  • 28,986
21

Use the gcalccmd from gnome-calculator (>=13.04) or gcalctool (<13.04) package. I think the package is installed by default

% gcalccmd
> 2+3
5
> 3/2
1.5
> 3*2
6
> 2-3
−1
> 
Flint
  • 3,201
12

Another solution I haven't seen mentioned here is Qalculate (qalc).

sudo apt-get install qalc

for the CLI version,

sudo apt-get install qalculate-gtk

for the GUI.

It has a bunch of features such as:

  • support for units: e.g. 20 m / s * 12 h = 864 kilom
  • built-in constants such as pi, e, c, avogadro
  • many built-in functions: e.g. sin(pi) = 0, gamma(4) = 6, 5! = 120, log(1024, 2) = 10
  • unit conversion, e.g:

> 120 in
120 * inch = 120 in
> convert cm
120 in = 304.8 centim

  • symbolic calculation, e.g. (x + y)^2 = x^2 + 2xy + y^2
  • integration, e.g. integrate 3*x^2 = x^3, diff sin(x), pi
  • built-in help, e.g. help convert, help integrate
  • tab completion of commands
  • everything is translated, e.g. my system is in Dutch, so I can write both factorial(5) and faculteit(5).
  • and more...

You say you want to use it without prefixes, well... you can use it with a prefix:

$ qalc 5 ft + 3 cm (5 * foot) + (3 * centim) = 1.554 m

as well as running it as a REPL.

JW.
  • 1,396
11

Here's a quick shell script for this:

#!/bin/bash
echo "$@" | bc

Save this as "c", then put it somewhere in your path (such as /bin), then mark it executable.

# nano /bin/c
# chmod +x /bin/c

From now on, you can run calculations in the terminal like this:

$ c 10000-9000
1000
8

Here's a modification of the appropriate part of /etc/bash.bashrc (on Ubuntu 10.04) that will modify the command_not_found handler to run the shell's expression evaluator if the first character of the unknown command is a number or - or +.

You'll be able to do any shell arithmetic this way; see http://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic for a list of arithmetic operators.

Note that if the expression you want to evaluate contains a *, you will have to quote the * with \ or quotes since the shell will do filename expansion before deciding which command to run. Same thing for other operators like >>.

Put this in your ~/.bashrc, then type . ~/.bashrc and try it out.

# if the command-not-found package is installed, use it
if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found ]; then
    function command_not_found_handle {
        if [[ $1 == [0-9+-]* ]]; then
           echo $(( $@ ))
        elif [ -x /usr/lib/command-not-found ]; then
           /usr/bin/python /usr/lib/command-not-found -- $1
           return $?
        elif [ -x /usr/share/command-not-found ]; then
           /usr/bin/python /usr/share/command-not-found -- $1
           return $?
        else
           return 127
        fi
    }
fi

Sample output: (I am typing cta, a typo, just to test that our new command_not_found handler will still try to look for unknown commands).

mp@ubuntu:~$ cta
No command 'cta' found, did you mean:
 Command 'cda' from package 'xmcd' (universe)
 Command 'cat' from package 'coreutils' (main)
cta: command not found
mp@ubuntu:~$ 9000-1000
8000
7

dc! It's part of coreutils, so it's installed on OS X, Ubuntu, and pretty much EVERYTHING else. It's an RPN calculator, so if you don't like those, it's not for you.

Very basic commands are as follows (manpage has all the syntax that I didn't include. Exponentiation, anyone?)

You only need spaces between numbers. They are ignored in all other cases.

Typing a number pushes it to the top of the stack.

+ Adds top 2 items in stack, then pushes result to stack (`2 4 +p` outputs 6)
- Subtracts top 2 items in stack, then pushes result to stack (`4 2 -p` outputs 2)
* Multiplies top 2 items in stack, then pushes result to stack (`6 5 *p` outputs 30)
/ Divides top 2 items in stack, then pushes result to stack (`54 7 /p` outputs 8)
p Print top item in stack, without destroying it
c Clear stack
r Swap top 2 items on stack
d Duplicate top item on stack
k Pops top item off stack, using it to determine precision (so 10 k would print 10 numbers after the decimal point). Default is 0, so it won't do floating point math by default.
n Pops top value off stack, then sends to stdout without a trailing newline
f Dump stack. Useful for finding what something does
6

I use Octave for this sort of thing: http://www.gnu.org/software/octave/

You can install it with

sudo apt install octave

It's pretty much a matlab clone (apologies if this is an over simplification) which can be used in the terminal by typing octave. Install sudo apt-get install octave

Its not quite what you want but I thought I'd add it as an alternative to python.

Example usage:

~ $ octave -q
octave:1> 9000 - 8000
ans =  1000
octave:2> 
Andy T
  • 161
5

You can use also use awk to do some arithmetic calculations on terminal,

echo 10000 9000 | awk '{print $1-$2}'
1000
echo 10000 9000 | awk '{print $1+$2}'
19000
echo 10000 9000 | awk '{print $1/$2}'
1.11111
echo 10000 9000 | awk '{print $1*$2}'
90000000
Avinash Raj
  • 80,446
5

I like wcalc a lot. It's a command line scientific calculator . Easy to find in Ubuntu Software Center, or just use apt-get.

sudo apt-get install wcalc

It accepts command line arguments as well as has "shell" mode:

# simple operation
$ wcalc 2+2
 = 4
# Quoting is necessary to prevent shell from evaluating parenthesis
$ wcalc "(2+2)*10"                                                                                    
 = 40
$ wcalc "sqrt(25)"                                                                                    
~= 5
# in shell mode you can evaluate multiple commands repeatedly
$ wcalc
Enter an expression to evaluate, q to quit, or ? for help:
-> 12*20+1
 = 241
-> sin(90)
 = 1
-> sin(pi/2)
 = 0.0274121

And if someone is in engineering, like myself, you could make use of GNU Octave. It can do all sorts of things, graphing, solving simultaneous equation. Plus it's a free alternative to Matlab

4

simple way is to call python.

Example:

>  python -c 'print 10000-9000'
3

What I have found is , I can't trust expr, bc or in-built Shell options. Hence I used Perl which would be normally installed in *linux distro's

perl -le 'printf "%.0f", eval"@ARGV"' "($VAL2-$VAL1)"

The above calculation will subtract $VAL1 from $VAL2 and print with no decimal places (0f)

Benefit with using Perl is (details of Pros & cons listed here)

  • Better error capture (divide by 0 won't stop the calculation)
  • Can provide formulae in a config file. No need to escape using complex regex
3

You may add following function to your .bashrc file:

function = {
  echo "$@" | bc -l
}

Note that -l flag is very important. Without it, use of bc gives 5 / 2 = 2.

As it was menthioned above, calculations may be done using = sign in front of formula.

vdm
  • 31
2

In the past, I've used wcalc and a little program called e that's pretty much impossible to google for. Now I use a python script to do this, which uses some features of e like the square brackets. wcalc is still nice because it can do arbitrary precision and unit conversion, but I almost never use those features.

#!/usr/bin/env python3

"""
This is a very simple command line calculator.  It reads in all
arguments as a single string and runs eval() on them.  The math module
is imported so you have access to all of that.  If run with no
arguments, it allows you to input a single line expression.  In the
case of command line args, square brackets are replaced with round
parentheses, because many shells interpret round parentheses if they
are not quoted.
"""

import sys, numbers
import cmath, math

args = sys.argv[1:]

if len(args) < 1:
    expr = input()
else:
    expr = " ".join(args[:])
    expr = expr.replace("[", "(").replace("]", ")")

def log2(x):
    """Return the base-2 logarithm of x."""
    return cmath.log(x, 2)

# the smallest number such that 1+eps != 1
# (this is approximate)
epsilon = sys.float_info.epsilon

env = math.__dict__
env.update(cmath.__dict__)
env = {k:v for k,v in env.items() if not k.startswith("__")}
env["eps"] = epsilon
env["log2"] = log2
env["inf"] = float("inf")
env["nan"] = float("nan")

res = eval(expr, env)
# throw away small imaginary parts, they're probably just due to imprecision
if (isinstance(res, numbers.Number)
    and res != 0
    and abs(res.imag)/abs(res) < 10*epsilon):
    res = res.real

print(str(res).replace("(", "[").replace(")", "]"))

Here's how to use it (assuming that the script has been saved as e and put somewhere in the $PATH):

$ e e**[pi*1i]
-1.0
$ e hex[10**3]
0x3e8
$ e "[0o400+3]&0xff" # need quotes because of '&'
3
jpkotta
  • 230
2

use "bc" command and then u can do calculation

example

[root@vaibhav ~]# bc

----------these lines will genrate automaicaly---------------

right 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 

---------------enter your calculation here---------------------------------------


10+2   

12

To use bc without the warranty note write in terminal bc -q

example

[root@vaibhav ~]# bc -q
10+2
12
sourav c.
  • 46,120
2

You can use bind and bash C-a and C-e to control the output. For example, execute this in your shell:

bind '"\C-j": "\C-aecho $(( \C-e )) \C-m"'

Now type any arithmetic operation like 10 + 15 and press Ctrl+J:

$ echo $(( 10 + 15 )) 
25

You will get this. Now, how is it done?

  • bind this command changes the binding of your bash, like shortcut keys.
  • \C-j this is the bash equivalent to Ctrl + J, this is what key combination we would like to add to our command.
  • \C-a this takes us to the start of the line.
  • echo $(( this writes echo $(( at the start.
  • \C-e takes us to the end of the line
  • )) closes our previous parenthesis
  • \C-m this is the equivalent to return key.

You can write this into your ~/.inputrc file:

"\C-j": "\C-aecho $(( \C-e )) \C-m"

Of course, the other answers are valid too! Just tweaked a bit:

  • bc: "\C-j": "\C-aecho " \C-e " | bc \C-m"
  • apcalc: "\C-j": "\C-acacl \C-m"
  • python: "\C-j": "\C-apython3 -c "print( \C-e )" \C-m"
  • any others?

You can change Ctrl + J to whatever you like, but remember, try not to change it for something that already has a binding ;).

Resource:

Braiam
  • 69,112
1

awk is built in so I created a little wrapper function in my ~/.bashrc function and will use it in future projects. Here's how to use it:

$ a=2.2; b=3.3

$ math c = $a / $b
$ echo $c
0.666667

$ math c = $a * $b
* not allowed, use x to multiply

$ math c = $a x $b
$ echo $c
7.26

$ math c = $a - $b
$ echo $c
-1.1

Here's the function:

math () {

    [[ $2 != "=" ]] && { echo "Second parm must be '='"; return 1; }

    # Declare arg as reference to argument provided (Bash 4.3 or greater)
    declare -n mathres=$1

    math_op="$4"    # '*' as parameter changes operator to 'aptfielout' and
                    # operand2 to 'aptfilein' so force 'x' instead.
    [[ $math_op == "aptfielout" ]] && \
        { echo "* not allowed, use x to multiply"; return 2;}
    [[ $math_op == "x" ]] && math_op="*"

    mathres=$(awk "BEGIN { print ($3 $math_op $5) }")

#    test=$(awk "BEGIN { print ($3 $math_op $5) }")
#    echo "1:$1 2:$2 3:$3 4:$4 5:$5 result=$test"

} # math
1

Genius

When you need something more powerful than bc. For example, Genius lets you perform exponentiation with rational (non-integer) exponents:

genius --exec='81^0.75'

prints

27.0

1

Create a Terminal Calculator

Put the following in your .bashrc file

function calc
{
 echo "${1}"|bc -l;
}

Or, run it at the shell prompt. Now "calc" from the shell will work as follows:

$ calc 3+45
   48

All functions with a "(" or ")" must be enclosed in quotes.

muru
  • 207,228
1

You can also use printf shell builtin to do arithmetic calculations on terminal.

printf `expr $num1 + $num2`   # num1,num2 are  variables which stores numbers as values.

Example:

$ printf "$(expr 10000 + 9000)\n"
19000
$ printf "$(expr 10000 - 9000)\n"
1000
Avinash Raj
  • 80,446
1

You can use the python interpreter for calculation. Here's a tutorial on how to do so.

Python 2 and python 3 are installed in Ubuntu by default.

$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 2+2
4
>>> 3*5
15
Zanna
  • 72,312
0

There is one-step way to accomplish exactly what you want. All you need to do is set the shell for your account to /bin/bc.

Braiam
  • 69,112