Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I was wondering, is it possible to do simple maths in bash? I'm thinking something like, =25-5 would print out 20 or something.

Can this be done easily?

Thank you

share|improve this question
up vote 13 down vote accepted

Just type "bc" no quote into the terminal. Then type all the math stuff in after that.

share|improve this answer
    
Just for clarity it would be like that : echo 25-5 | bc – Medhat Helmy May 13 at 9:17

If we are really talking about Bash, not Bourne Shell (sh) or other shells, it's easy.

Bash can compute basic expressions with $((expression)) and here's an example on how you might like to use it:

 a=3
 b=4
 c=$((7*a+b))
 echo $c

or for interactive use, just

 echo $((7*3+4))
share|improve this answer
    
It does seem to be proper bash, since that works. I am ssh-ing into one of my universities clusters – Kurru Mar 11 '11 at 0:59
3  
The $((expression)) syntax is part of the POSIX sh standard, and derived from ksh. – geekosaur Mar 11 '11 at 1:05
4  
Bash can only do integer arithmetic. It cannot do floating point arithmetic like ksh93 or zsh – fpmurphy1 Mar 11 '11 at 2:27

There are a number of command-line utilities for doing simple calculations:

$ expr 100 \* 4
400

$ echo '100 * 4' | bc
400

to name just two of them. Be careful doing multiplication as if you don't escape your * the shell may try and interpret it as a wildcard.

share|improve this answer

Well your question is answered, but consider this:

Most of the linux distros have python preinstalled, so why not use it?

Just type

python

in the terminal and then do all the arithmetics you want, like

2+2

Will output 4 :)

share|improve this answer
    
very nice :) thanks – Kurru Mar 11 '11 at 0:58
    
On my computer, typing python takes nearly two seconds to start. Rather annoying if you just want to do something simple like 2+2. – ShreevatsaR Mar 11 '11 at 7:14

Another is AWK:

awk 'BEGIN {4 + 3 / 12}'
share|improve this answer

Or Ruby. :)

Although it may not come pre-installed, it is pretty quick.

Type irb, then 2+2.

Or just ruby -e 'p 2+2'

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .