Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Using echo "20+5" literally produces the text "20+5"

What command can I use to get the numeric sum, e.g. 25 in this case.

Also, what's the easiest way to do it just using bash for floating point, e.g.
echo $((3224/3807.0)) gives 0 :(

Using either the basic command shell ('command line') itself or through using languages that are available at the command line.

share|improve this question
1  
Good Job Everyone ! Looks like we're heading for a community wiki fast on this one ! –  Michael Durrant Jun 14 '12 at 20:18
    
If you're going with bc, it may be worth your while to read about the -l option in the man page. –  glenn jackman Jun 14 '12 at 21:39
    
I assume author is asking for bash command line, while answers all tend to diversify to all kinds of scripting languages. –  zinking Jun 15 '12 at 3:21
1  
man bash → /expression –  ДМИТРИЙ МАЛИКОВ Jun 15 '12 at 7:46
1  
@zinking Well, bash is designed to be conveniently able to easily invoke the interpreters for a large number of other scripting language. –  Random832 Jun 15 '12 at 17:35

15 Answers 15

up vote 135 down vote accepted

There are lots of options!!!

Summary

$ echo $((20.0/7))
$ zcalc
$ bc <<< 20+5/2
$ bc <<< 'scale=4;20+5/2'
$ expr 20 + 5
$ calc 2 + 4
$ node -pe 20+5/2  # Uses the power of JavaScript, e.g. : node -pe 20+5/Math.PI
$ echo 20 5 2 / + p | dc 
$ echo 4 k 20 5 2 / + p | dc 
$ perl -E "say 20+5/2"
$ python -c "print 20+5/2"
$ python -c "print 20+5/2.0"
$ clisp -x "(+ 2 2)"
$ lua -e "print(20+5/2)"
$ php -r 'echo 20+5/2;'

.

$ ruby -e 'p 20+5/2'
$ ruby -e 'p 20+5/2.0'
$ guile -c '(display (+ 20 (/ 5 2)))'
$ guile -c '(display (+ 20 (/ 5 2.0)))'
$ slsh -e 'printf("%f",20+5/2)'
$ slsh -e 'printf("%f",20+5/2.0)'
$ tclsh <<< 'puts [expr 20+5/2]'
$ tclsh <<< 'puts [expr 20+5/2.0]'
$ sqlite3 <<< 'select 20+5/2;'
$ sqlite3 <<< 'select 20+5/2.0;'
$ echo 'select 1 + 1;' | sqlite3 
$ psql -tAc 'select 1+1'
$ R -q -e 'print(sd(rnorm(1000)))'
$ r -e 'cat(pi^2, "\n")'
$ r -e 'print(sum(1:100))'
$ smjs
$ jspl

Details

You can use POSIX arithmetic expansion echo $((...)):

$ echo $((20+5))
25
$ echo $((20+5/2))
22

ksh93 and zsh do support floats there:

$ echo $((4*atan(1)))
3.14159265358979324

(in zsh, you need zmodload zsh/mathfunc to get the math functions like atan above).


Interactively with zsh:

$ autoload zcalc
$ zcalc
1> PI/2
1.5708
2> cos($1)
6.12323e-17
3> :sci 12
6.12323399574e-17

Witch (t)csh:

% @ a=25 / 3; echo $a
8

In the rc shell family, akanga is the one with arithmetic expansion:

; echo $:25/3
8

Or bc (see below for interactive mode): Mnemonic: B est C alculator

$ bc <<< 20+5/2
22
$ bc <<< 'scale=4;20+5/2'
22.5000

bc interactive mode:

$ 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'. 
5+5
10

2.2+3.3
5.5

Or Rush's solution, expr (no interactive mode):

$ expr 20 + 5
25
$ expr 20 + 5 / 2
22

or DQdims's calc (required sudo apt-get install apcalc):

$ calc 2 + 4
6

Or manatwork's solution, node (interactive mode: node; output function not needed):

$ node -pe 20+5/2  # Uses the power of JavaScript, e.g. : node -pe 20+5/Math.PI
22.5

Or Arcege's solution, dc (interactive mode: dc):

Which is even more fun since it works by reverse polish notation.

$ echo 20 5 2 / + p | dc 
22
$ echo 4 k 20 5 2 / + p | dc 
22.5000

But not as practical unless you work with reverse polish notation a lot.


Or Perl (interactive mode: perl -de 1):

$ perl -E "say 20+5/2"
22.5

Or Python (interactive mode: python; output function not needed):

$ python -c "print 20+5/2"
22
$ python -c "print 20+5/2.0"
22.5

Or if you have clisp installed, you can also use polish notation:

$ clisp -x "(+ 2 2)"

Or Marco's solution, lua (interactive mode: lua):

$ lua -e "print(20+5/2)"
22.5

PHP (interactive mode: php -a):

$ php -r 'echo 20+5/2;'
22.5

Ruby (interactive mode: irb; output function not needed):

$ ruby -e 'p 20+5/2'
22
$ ruby -e 'p 20+5/2.0'
22.5

Guile (interactive mode: guile):

$ guile -c '(display (+ 20 (/ 5 2)))'
45/2
$ guile -c '(display (+ 20 (/ 5 2.0)))'
22.5

S-Lang (interactive mode: slsh; output function not needed, just a ; terminator):

$ slsh -e 'printf("%f",20+5/2)'
22.000000
$ slsh -e 'printf("%f",20+5/2.0)'
22.500000

Tcl (interactive mode: tclsh; output function not needed, but expr is):

$ tclsh <<< 'puts [expr 20+5/2]'
22
$ tclsh <<< 'puts [expr 20+5/2.0]'
22.5

SQLite (interactive mode: sqlite3):

$ sqlite3 <<< 'select 20+5/2;'
22
$ sqlite3 <<< 'select 20+5/2.0;'
22.5

Various SQL's:
SQLite:

echo 'select 1 + 1;' | sqlite3 

MySQL:

mysql -BNe 'select 1+1'

PostgreSQL:

psql -tAc 'select 1+1

_The options on mysql and postgres stop the 'ascii art' image !


R in plain mode - lets generate 1000 Normal random numbers and get the standard deviation and print it

$ R -q -e 'print(sd(rnorm(1000)))'
> print(sd(rnorm(1000)))
[1] 1.031997

R using the littler script - lets print pi squared

$ r -e 'cat(pi^2, "\n")'
9.869604
$  r -e 'print(sum(1:100))'
[1] 5050

PARI/GP, an extensive computer algebra system for number theory, linear algebra, and many other things

$ echo "prime(1000)"|gp -q
7919                        // the 1000th prime
$ echo "factor(1000)" | gp -q
[2 3]
[5 3]                       // 2^3*5^3
$ echo "sum(x=1,5,x)" | gp -q
15                          // 1+2+3+4+5

Javascript shells:

$ smjs
js> 25/3
8.333333333333334
js>

$ jspl
JSC: 25/3

RP: 8.33333333333333
RJS: [object Number]
JSC:
Good bye...

$ node
> 25/3
8.333333333333334
>
share|improve this answer
1  
and bc is interesting: whatis bc -> An arbitrary precision calculator language Interesting! Thanks! –  Michael Durrant Jun 14 '12 at 14:48
    
@MichaelDurrant could you re-revise your edits, I must have rejected by mistake? –  lgarzo Jun 14 '12 at 15:06
    
added some bolding in. Looks ok –  Michael Durrant Jun 14 '12 at 15:10
1  
There is also dc, which is even more fun since it works by reverse polish notation. echo 20 5 + p | dc But not as practical unless you work with reverse polish notation a lot. –  Arcege Jun 14 '12 at 15:11
2  
As a variation on the bc approach, I added the following function (that I found on stackexchange somewhere) to my .bashrc file. I can just enter calc 2+3 and get 5. ## Command line calculator calc () { bc -l <<< "$@" } –  Joe Jun 16 '12 at 18:59

Nobody has mentioned awk yet?

Using bash functions, and awk math power, just define this (one line) function:

calc(){ awk "BEGIN { print "$*"}"; }

Then just execute things like calc 1+1 or calc 5/2

Note: To make the function always available, add it to ~/.bashrc

Of course, a little script named "calc" with the following contents:

#!/bin/bash
awk "BEGIN { print $* }"

could also work.

share|improve this answer
    
Wow this is the best, even supports floats. It works without installing anything! –  CMCDragonkai Jun 4 at 2:40

Gnuplot

gnuplot - an interactive plotting program
Follow the above link or type gnuplot form the prompt then help.
It's a program born to plot data, but can be used so too.

echo  "pr 20+5/2"  |  gnuplot          #  Lazy-note `pr` instead of print
22                                     #  Integer calculation & result
echo  "pr 20.+5/2"  |  gnuplot         #  Lazy-note `pr` instead of print
22.0                                   #  Floating point result
echo  "pr sin(2*pi/3.)"  |  gnuplot    #  Some functions ...
0.866025403784439

Root (or some C interpreter)

The ROOT system provides a set of OO frameworks with all the functionality needed to handle and analyze large amounts of data in a very efficient way...

You can use it as C interpreter, CINT, or you can use one of the many many others. IMHO, it's huge, complex, powerful, and not always friendly but can give big satisfaction too.

If you really do not want to listen the little voice inside you that cites Confucio and you are ready to break a (butter)fly on the wheel you can use root too. In this case -l is mandatory to avoid to show splash screen...

echo  "20+5/2"   | root -l
(const int)22
echo  "20+5/2."  | root -l
(const double)2.25000000000000000e+01
share|improve this answer

Use the GNU Multiple Precision Arithmetic Library through the supplied run-expr program:

  • Download and extract(you will need lzip): tar --lzip -xvf gmp-5.1.3.tar.lz
  • In the top directory, ./configure and make (no need to install)
  • In demos/expr, do make libexpr.a, then make run-expr
  • Create a symbolic link from your ~/bin directory: ln -s /path/to/expr/run-expr .
  • Add an alias for easy use; for instance alias calcf='run-expr -f' for floating point evaluation

Output:

# calcf '2/3'
"2/3" base 0: result 0.666666666666666666667e0

From the run-expr.c file:

Usage: ./run-expr [-z] [-q] [-f] [-p prec] [-b base] expression...

   Evaluate each argument as a simple expression.  By default this is in mpz
   integers, but -q selects mpq or -f selects mpf.  For mpf the float
   precision can be set with -p.  In all cases the input base can be set
   with -b, or the default is "0" meaning decimal with "0x" allowed.

See the manual for function classes differences and details.

share|improve this answer

I use a little python script that will evaluate a python expression and print the result, then I can run something like

$ pc '[i ** 2 for i in range(10)]'
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

the script is:

#!/usr/local/bin/python3

import sys
import traceback
from codeop import CommandCompiler

compile = CommandCompiler()
filename = "<input>"
source = ' '.join(sys.argv[1:]) + '\n'

try:
    code = compile(source, filename) 
except (OverflowError, SyntaxError, ValueError):
    type, value, sys.last_traceback = sys.exc_info()
    sys.last_type = type
    sys.last_value = value
    if filename and type is SyntaxError:
        # Work hard to stuff the correct filename in the exception
        try:
            msg, (dummy_filename, lineno, offset, line) = value.args
        except ValueError:
            # Not the format we expect; leave it alone
            pass
        else:
            # Stuff in the right filename
            value = SyntaxError(msg, (filename, lineno, offset, line))
            sys.last_value = value
    lines = traceback.format_exception_only(type, value)
    print(''.join(lines))
else:
    if code:
        exec(code)
    else:
        print('incomplete')

Unfortunately I don't remember where I borrowed most of the code from, so I can't cite it.

share|improve this answer
    
wouldn't print(eval(' '.join(sys.argv[1:]))) do the same thing? –  g.rocket Oct 8 at 5:02

SQLite:

echo 'select 1 + 1;' | sqlite3 

MySQL:

mysql -e 'select 1 + 1 from dual;'

PostgreSQL:

psql -c 'select 1 + 1 as sum;'
share|improve this answer
2  
Some minor details worth to mention: 1) from dual is needed by Oracle, MySQL is able to select without from clause. 2) PostgreSQL not requires the alias. 3) The ; is only required by SQLite. 4) MySQL and PostgreSQL will work only if they are able to connect to a database server. 5) MySQL and PostgreSQL will draw ASCII-art table around the results. To get only the value: mysql -BNe 'select 1+1' and psql -tAc 'select 1+1. –  manatwork Jun 16 '12 at 15:00

Since no-one else has mentioned it, and though it's not strictly a calculator (but neither are all these general-purpose scripting languages), I'd like to mention units:

$ units "1 + 1"
        Definition: 2
$ units "1 lb" "kg"
        * 0.45359237
         / 2.2046226

Or, for less output so you can get just the number to use in $() to assign to something:

$ units -t "1 + 1"
2
$ units -t "1 lb" "kg"
0.4539237

And it even does temperature conversions

$ units -t "tempC(20)" "tempF"
68

To get the temperature conversion in an expression for further calculation, do this:

$ units -t "~tempF(tempC(20))+1"
68.1
share|improve this answer
$> ghc -e '20 + 5'
25
it :: Integer
share|improve this answer
3  
Is that ghc meaning Glasgow Haskell Compiler? –  manatwork Jun 15 '12 at 7:32
    
taking a pass on programs I need to install but thx. –  Michael Durrant Jun 21 '12 at 14:07

I can't believe to read "the power of JavaScript" (but I had to upvote the answer for the other parts, except perl of course.

Practically, for the simple cases where integer arithmetic is sufficient, I use the buildin $((...)) and recommend it. Else, in almost all cases echo "..." | bc is sufficient.

For some arithmetic operations like statistics, matrix operations and more R is the better tool:

echo 25 + 5 | R --vanilla

and for small datasets and graphical throw away results, oocalc is a nice utility.

share|improve this answer

I like to fire up Python and use it as an interactive calculator (but then again, I'm a Python programmer).

share|improve this answer
    
me too! Python is my swiss army knife –  Levon Jun 14 '12 at 23:47
    
I always have one window in screen just running Python. –  Arcege Jun 15 '12 at 18:54
    
pythonpy (github.com/russell91/pythonpy) is a nice way to do this and other things in python syntax without having to fire up an interactive shell: py '3.2 * 5' => 16 –  singular Sep 13 at 6:30

For console calculations, I use concalc. (sudo aptitude install concalc)

After that, just type concalc and hit enter. It won't supply a prompt, but just type in the your calculation (no spaces) and hit enter, and on the next line, it'll give you the numeric value.

share|improve this answer

You can use calc:

If you just enter calc with no other arguments it enters an interactive mode where you can just keep doing math. You exit this by typing exit:

C-style arbitrary precision calculator (version 2.12.3.3)
Calc is open software. For license details type:  help copyright
[Type "exit" to exit, or "help" for help.]

; 2+4
6
; 3+5
8
; 3.4+5
8.4
; 2^4
16
; exit

Or you use it with the expression as an argument and it will provide the answer and then exit

$calc 2 + 4
    6
$

calc is similar to bc, I just like the way it behave as default better

share|improve this answer
1  
You don't need to enter interactive mode, unless you particularly want to, eg: calc -e '2+4; 3+5; 3.4+5; 2^4 prints 4 output lines, or just calc -e 33+(3^3).. +1 I like the idea of using something called 'calc' for a calculator :) –  Peter.O Jun 14 '12 at 18:47
1  
I've just realized that the -e option is not needed when there is only one expression... neat!.. –  Peter.O Jun 15 '12 at 1:19

The mentioned solutions are fine for very simple calculations, but very error-prone. Examples:

# without spaces 20+5 literally produces 20+5
expr 20+5
→ 20+5

# bc's result does't give the fractional part by default
bc <<<
9.0/2.0
→ 4

# expr does only integer
expr 9 / 2
→ 4

# same for echo
echo $((9/2))
→ 4

# echo chokes on floats
echo $((9.0/2.0))
→ bash: 9/2.0: syntax error: invalid arithmetic operator (error token is ".0")

# expr also has problems with floats
expr 9.0 / 2.0
→ expr: non-integer argument

A syntax error like the last ones never get unnoticed, but integer responses with a discarded float part can easily get unnoticed and lead to wrong results.

That's why I always use a scripting language like Lua for that. But you can choose any scripting language that you're familiar with. I just use Lua as an example. The advantages are

  • a familiar syntax
  • familiar functions
  • familiar caveats
  • flexible input
  • spaces usually don't matter
  • floating point output

Examples:

lua -e "print(9/2)"
→ 4.5

lua -e "print(9 / 2)"
→ 4.5

lua -e "print(9.0/2)"
→ 4.5

lua -e "print (9 /2.)"
→ 4.5

lua -e "print(math.sqrt(9))"
→ 3
share|improve this answer
2  
bc's result is not integer, just rounded to scale, who's default value is 0. So bc <<< 'scale=4;9.0/2.0' if you want the fractional part. –  manatwork Jun 14 '12 at 16:16
    
Thanks for the correction. But still, it's error prone. Will I remeber to add scale if I use bc in a couple of weeks? Probably not. And even if there's a way to change it permanently, it will bite you if you're on a system with the default settings. –  Marco Jun 14 '12 at 16:26
2  
Personally I do remember about scale since I met bc first time years ago. But I always forgot whether the output function in lua is put or puts. ;) –  manatwork Jun 14 '12 at 17:06
    
Just count bc as one of the scripting languages. I always know whether I need integer results or not - if integer is alright I stay in bash, else I rarely have reason to use bc. For lua, you have to remember -e, print and parenthesis. –  user unknown Jun 14 '12 at 21:39
2  
Just always use bc -l rather than plain bc, then never worry about scale. –  Dalker May 1 '13 at 19:54

You could use bc. E.g.,

$ echo "25 + 5" | bc
30

Alternatively bc <<< 25+5 will also work.

Or interactively, if you want to do more than just a single simple calculation:

$ 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'. 
25 + 5
30

bc -q will jump into bc right away without the header/copyright info. For more information see the bc man page

This page also shows how to set up an alias or function to do calculation like this:

c "25 + 5" 

and get the result

share|improve this answer
1  
+1 for both pipe ("|") and interactive mode options for bs. Does one ctrl-d to exit? –  Michael Durrant Jun 14 '12 at 14:49
1  
@MichaelDurrant Yes, ^D will do the trick as will quit –  Levon Jun 14 '12 at 14:50

There are many ways to calculate. For simple expressions you can use bash itself:

echo $((20+5))

or expr:

expr 20 + 5

And for complex cases there is great tool bc:

echo "20+5" | bc

Btw, bc can calculate even very complex expression with roots, logarithms, cos, sin and so on.

share|improve this answer
    
I added your expr option to the accepted answer. Had to pick one to accept and centralize. –  Michael Durrant Jun 14 '12 at 15:11
1  
You're trying to execute expr 20+5. You need to type spaces between numbers and plus to make it work: expr 20 + 5. That's important. –  rush Jun 22 '12 at 14:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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