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 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.

  • 1
    Maybe packages.ubuntu.com/saucy/apcalc ? – wakeup Nov 18 '13 at 2:44
  • 2
    It might be possible to hack something like that up with a kind of pre-hook; but that in itself can only be done in a really ugly and hackish way. No, I very much think it's not a good idea. Bash as a whole is meant as a plain IO scripting language, anything it does apart from that is more or less ad-hoc and doesn't work really well. Python on the other hand (or even e.g. Haskell) is a modern, all-purpose programming language with great syntax. So it would be just stupid not to use it. – leftaroundabout Nov 18 '13 at 9:16
  • 3
    In the same vein, you could also do something with the command_not_found hook, and try feeding the command to bc/calc/whatever if it looks vaguely like maths. It still feels a bit dirty, though. – chronitis Nov 18 '13 at 9:38
  • 1
    Wait, what exactly do you mean "switch to" python? and "without any extra prefixes"? Are you saying you want to be able to calculate things at the prompt without running a command? – Random832 Nov 19 '13 at 21:55
  • 2

25 Answers 25


Bash Arithmetic

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

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

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


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/+}"
    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"


$ = 16 + 0x10
272 (0x110)

$ = 16**3 + 16**4
69632 (0x11000)

Using bc

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

=() {
    local IFS=' '
    local calc="${*//p/+}"
    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 from 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 if 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 → *)
    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:

sin⁻¹() == asin()
cos⁻¹() == acos()
tan⁻¹() == atan()
sinh⁻¹() == asinh()
cosh⁻¹() == acosh()
tanh⁻¹() == atanh()
| improve this answer | |
  • Sorry for this late reply but the command you have given for gcalccmd doesn't work quite well. It shows Error 3 probably because of that stray whitespace. However this slightly modified one worked perfectly for me: echo -e "$calc\nquit"| gcalccmd | sed "s:^> ::g" – udiboy1209 Apr 4 '14 at 17:59
  • I built a scientific calc using R! function = { R -q --vanilla -e "$@" | grep -E '[^>](.*)' -o -x --color=never } – Morteza Milani Jul 10 '14 at 6:51
  • Hi, and thanks. That's pretty cool. BTW your substitution for 'x' make it fail for hex input, which otherwise works fine. Speaking of which, can I have the answer in 'hex' as well? eg. = 2 + 0x20 34 (0x22) – FractalSpace Oct 8 '15 at 21:12
  • Thanks. I meanwhile came up with python based solution: c(){ python -c "from math import *; print($*, hex($*))" } – FractalSpace Oct 9 '15 at 14:52
  • Bear in mind that bc is a really really annoying piece of software. – jwg Jul 26 '16 at 7:23

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

$ echo $((10000-9000))

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

$ echo "10000-9000" | bc

The bc program can do floating point arithmetic as well

$ echo "scale = 3; 0.1-0.09" | bc
| improve this answer | |
  • 11
    This is probably the closest you can get. To cut down on extra typing (though not eliminate it entirely) you can put a function in your ~/.bashrc: calc() NL { NL echo "$@" | bc NL } where NL is a newline. Then you can type calc 1234 + 768 (prints 2002), or any other formula that bc can interpret. You can of course use any function name, I just thought that calc fit nicely with what this does. – user Nov 18 '13 at 9:43
  • 4
    once python is more better than echo all the time. my opinion. – rɑːdʒɑ Nov 18 '13 at 12:07
  • 6
    You can use bc interactively as well, unless you need the echo for some other reason: just run bc and type your expression. Type Ctrl-D on its own line to exit. – Useless Nov 18 '13 at 12:39
  • if you made any automatic expression taking with the help of alias or something else then that would be great. – rɑːdʒɑ Nov 18 '13 at 19:13
  • 3
    No need to echo: bc <<< "2*2" – Bernhard Nov 20 '13 at 19:21

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
$ calc 5-2
$ calc 5*2          
$ calc 5/2
$ calc 5^2
$ calc 'sqrt(2)' 
$ calc 'sin(2)'
$ calc 'cos(2)'
$ calc 'log(2)'
$ calc 'sqrt(sin(cos(log(2))))^2'
$ # and so on...

For more information , view its man-page

| improve this answer | |
  • 2
    Thank you for answering , I see the answer has its own significance. I like more a bit about all those trigonometric functions calculations. any manual or somepage about what more it can do can improve you answer a lot. :) – rɑːdʒɑ Nov 18 '13 at 19:07
  • @rajagenupula man calc and calc help says everything. – Radu Rădeanu Nov 18 '13 at 19:39
  • 2
    My intension is , if someone looking at it it should be clear & quick. thank you. – rɑːdʒɑ Nov 18 '13 at 19:44
  • 1
    Actually you use calc help builtin to see a list of supported functions like sin() – Penghe Geng Mar 12 '15 at 4:59
  • Gives more decimals, so it is better suited for my purposes than built-in bash arithmetic. Thanks. – Mrmfldmn Oct 11 '16 at 21:35

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

... 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.

| improve this answer | |
  • 1
    I did mention that I dont want to switch into python – rɑːdʒɑ Nov 18 '13 at 2:43
  • 1
    @rajagenupula updated, also included the stuff i mentioned in chat. – Thomas Ward Nov 18 '13 at 2:46
  • bc isn't included anymore? – Random832 Nov 18 '13 at 15:47
  • 1
    As an aside, ipython is quite a bit more useful than the standard Python shell when it comes to doing calculations and the like. – Naftuli Kay Nov 19 '13 at 23:13
  • 1
    bc is included by default (at least in 16.04) – TJ Ellis May 7 '16 at 16:12

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,

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).

| improve this answer | |
  • everytime all those have to means not that much easy and flexible. Thank you. any improvements you can make it to look more simple & clear ? I'd love that. – rɑːdʒɑ Nov 18 '13 at 19:09
  • 1
    @rajagenupula You can put that in a function in your .bashrc (maybe with a shorter name: c, ? or +?) so you'll have it each terminal you open. – kiri Nov 18 '13 at 20:08
  • 1
    Beware: With Python 3 this works great, but if you want to use Python 2 you'll have to edit the snippet to: python2 -c "from __future__ import division; from math import *; print($*)" otherwise it will always do integer division, e.g. for calc 5/2 you would get 2 instead of 2.5. See here for reference: stackoverflow.com/a/183870/202504 – jmiserez Jan 22 '15 at 11:16
  • The Python solution may actually be better than apcalc in that you can import additional libraries, and it supports literal pi and e. I feel putting this as a separate script is more flexible and portable. Here is a simple gist for it: gist.github.com/jasongeng/279eb396c01e74beb9ef – Penghe Geng Mar 12 '15 at 5:20

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

% gcalccmd
> 2+3
> 3/2
> 3*2
> 2-3
| improve this answer | |
  • The best one till now.. No need to do extra thing and also installed by default.. man gcalccmd says: a console calculator. Simply, it is exactly what OP wants.. :) – Saurav Kumar Nov 18 '13 at 17:13
  • Thats cool , similar to bc, python, ocatve calculators. Thank you. – rɑːdʒɑ Nov 18 '13 at 19:12
  • Since gcalccmd is quite hard to type, it is good idea to add alias to it in ./bash_aliases like alias calc='gcalccmd' or if you want to make one-off calculations (with instant answer), you can add alias calc='gnome-calculator -s' - usage of the latter: calc 2000/1300 or calc 2+3. In that case, there is no need to exit calculator - it just gives you an answer and you do not need to type quit. – Rafal Apr 10 '14 at 10:37

Here's a quick shell script for this:

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
| improve this answer | |
  • You are superb , adding only one letter before the calculation means thats really cool idea. this is super for if i need to 2 to 3 calculations. I can go for python or some other for longer but shorter I choose this. Thank you for stopping by. – rɑːdʒɑ Nov 18 '13 at 19:11
  • 2
    I'd advise you to use echo "$@" | bc instead so you can put spaces in calculations more naturally – kiri Nov 18 '13 at 20:57
  • How about using = instead of c for the name of this command? Bash actually lets you use this as the name of a function. – Kaz Nov 18 '13 at 21:23
  • 1
    You can put programs into ~/bin (your home directory's bin) and ensure that /home/yourname/bin is in your PATH. – Kaz Nov 18 '13 at 21:23
  • @minerz029 Nice thinking. I have edited my answer accordingly. – user530873 Nov 19 '13 at 0:35

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.

| improve this answer | |

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 $?
           return 127

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
| improve this answer | |
  • is there any way we could add more support for calculations ? – rɑːdʒɑ Nov 18 '13 at 19:28
  • 1
    You can take the line that says echo $(( $@ )) and change it to, instead, run one of the more advanced calculator programs that other answerers have mentioned that take their arguments on the command line. – Mark Plotnick Nov 18 '13 at 19:30

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
| improve this answer | |
  • Just noticed, this doesn't answer the question (nor do any other answers). The question is how NOT to have any stuff in front of the equation (nor behind), and simply type say, 42 * 5 into a terminal, and have it output the answer – Yet Another User Nov 18 '13 at 20:09
  • 2
    Most of the answers don't apply. Typing 1+1 in a terminal will almost never work. So your answer is fine – kiri Nov 18 '13 at 20:10
  • @YetAnotherUser I think the only way is hacking into command-not-found (if it's installed) or doing something dirty in the bashrc... – Braiam Nov 18 '13 at 20:13

I use Octave for this sort of thing: http://www.gnu.org/software/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
octave:1> 9000 - 8000
ans =  1000
| improve this answer | |
  • Suggesting another way to accomplish the goal is fine in an answer, but you should provide more information about how the OP would use Octave to meet the stated needs and why it's a good alternative. – chaskes Nov 18 '13 at 14:58
  • 2
    +1 ,Octave , matlab,scilab,python all are similar but octave I need to install but python preinstalled. so I head to python by default. Thank you. – rɑːdʒɑ Nov 18 '13 at 19:06
  • from all that I tried (and I tried many!) octave is the only one to return non 0 on syntax error! thx! – Aquarius Power Nov 15 '14 at 22:40

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

echo 10000 9000 | awk '{print $1-$2}'
echo 10000 9000 | awk '{print $1+$2}'
echo 10000 9000 | awk '{print $1/$2}'
echo 10000 9000 | awk '{print $1*$2}'
| improve this answer | |
  • cool, awk (as octave) also returns non 0 on syntax error thx! – Aquarius Power Nov 15 '14 at 22:43
  • awk reduces need to install bc and you don't have to deal with overhead of python. – WinEunuuchs2Unix May 21 at 2:36

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

| improve this answer | |
  • ...combining that with @minerz029 is pretty neat: Place this in your ~/.bash_aliases: =() { wcalc "$@" } – Frank Nocke Feb 27 '17 at 8:22

simple way is to call python.


>  python -c 'print 10000-9000'
| improve this answer | |
  • can you mention something with scientific calculations. – rɑːdʒɑ Nov 20 '13 at 14:26
  • 1
    Do you want something like this? python -c 'import math;print math.log(2)' – user1251007 Nov 26 '13 at 11:03

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
| improve this answer | |
  • but everytime that command means little bit problem any way. are there any perl based calculators to be used in terminal ? – rɑːdʒɑ Nov 18 '13 at 19:04

use "bc" command and then u can do calculation


[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---------------------------------------



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


[root@vaibhav ~]# bc -q
| improve this answer | |
  • bc is already explained and included. – Braiam Nov 19 '13 at 13:16

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.

| improve this answer | |

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 )) 

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 ;).


| improve this answer | |
  • Ctrl + J does already have a binding, it submits the line (like Enter) This is actually a pretty smart answer, though ;) – kiri Nov 20 '13 at 20:25

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()
    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 = {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]
$ e hex[10**3]
$ e "[0o400+3]&0xff" # need quotes because of '&'
| improve this answer | |
  • an example will make this looks more clear.Thank you. – rɑːdʒɑ Nov 18 '13 at 19:04

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.


$ printf "$(expr 10000 + 9000)\n"
$ printf "$(expr 10000 - 9000)\n"
| improve this answer | |
  • 3
    This way you're using expr(which is not builtin) to calculate the result, printf is redundant here – Javier López Nov 3 '15 at 2:05

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
>>> 3*5
| improve this answer | |

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

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

| improve this answer | |

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

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

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

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

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
| improve this answer | |


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'



| improve this answer | |

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.

| improve this answer | |
  • 3
    Could you please elaborate? Pressume OP doesn't know how to change the shell. – Braiam Dec 11 '13 at 12:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.