48

Issue:

Every now and then I need to do simple arithmetic in a command-line environment. E.G. given the following output:

Disk /dev/sdb: 256GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags: 

Number  Start   End     Size    File system     Name  Flags
 1      1049kB  106MB   105MB   fat32                 hidden, diag
 2      106MB   64.1GB  64.0GB  ext4
 3      64.1GB  192GB   128GB   ext4
 5      236GB   256GB   20.0GB  linux-swap(v1)

What's a simple way to calculate on the command line the size of the unallocated space between partition 3 and 5?

What I've tried already:

bc

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'. 
236-192
44
quit

where the bold above is all the stuff I need to type to do a simple 236-192 as bc 1+1 echoes File 1+1 is unavailable.

expr

expr 236 - 192

where I need to type spaces before and after the operator as expr 1+1 just echoes 1+1.

11
  • 4
    If you're intending to do this interactively, you don't need to type quit into bc; pressing ctrl-D will do, as it will in any interactive program.
    – marcelm
    Nov 6 '18 at 19:53
  • 3
    dc is (IMO) far superior to bc. Nov 6 '18 at 22:53
  • 1
    I think the unallocated space between ptn 3 and 5 should be 236 - 192, and not 236 - 128? Nov 6 '18 at 23:02
  • @DigitalTrauma good eye! (It was just an example and no one spotted that one!)
    – Fabby
    Nov 7 '18 at 0:10
  • 1
    @JanM. I'm the one who upvoted.... ;-)
    – Fabby
    May 3 '19 at 19:17

21 Answers 21

63

You can reduce the amount of verbosity involved in using bc:

$ bc <<<"236-192"
44
$ bc <<<"1+1"
2

(assuming your shell supports that).

If you’d rather have that as a function:

$ c() { printf "%s\n" "$@" | bc -l; }
$ c 1+1 22/7
2
3.14285714285714285714

(-l enables the standard math library and increases the default scale to 20.)

Store the c definition in your favourite shell startup file if you want to make it always available.

4
  • 3
    bc<RET>236-128<RET>quit<RET> is 16 keystrokes. bc<<<"236-128"<RET> is 15 keystrokes. Not what I would call "greatly reduced amount of typing" :-) In addition, bc can be exited with ^D, so first option is reduced to 13 keystrokes (counting ^D as two).
    – L. Levrel
    Nov 6 '18 at 16:24
  • Right, it’s more about verbosity ;-). Nov 6 '18 at 16:26
  • 3
    @L.Levrel With the function it's just c 1+1 which is just what I needed! :-) (answer updated to make that clearer)
    – Fabby
    Nov 6 '18 at 16:49
  • And if you do floating point : c 'scale=2; 17/3' (or better, have scale a variable used inside the 'c()' function, and define it's value whenever you need to have n decimal digits. default is 0.) Nov 7 '18 at 14:03
38

Summary

There are several solutions listed (shell, awk, dc, perl, python, etc.).

A function may be defined with any option (gawk seems to be the most flexible to use)

c () { local in="$(echo " $*" | sed -e 's/\[/(/g' -e 's/\]/)/g')";
       gawk -M -v PREC=201 -M 'BEGIN {printf("%.60g\n",'"${in-0}"')}' < /dev/null
     }

And use it like:

$ c 236- 192
44

Shell

The simplest calc in CLI is the CLI (shell) itself (If IFS is default):

$ echo $(( 22 + 333 ))
355

Spaces could be omitted:

$ echo $((22*333))
7326

As it is part of POSIX almost all shells have it. And it includes most of C language math functionality (except that zsh has a different precedence, set C_PRECEDENCES to restore it to a compatible value):

$ echo $((22*333^2))
7324

And some shells have most of the C language math syntax (including comma):

$ echo $((a=22,b=333,c=a*b,c))
7326

But it is only integer math (and usually less than 263 in present day OSes) in some shells:

$ echo $((1234/3))
411

$ zsh -c 'echo $((2**63))'
-9223372036854775808

Some shells could do floating math:

$ ksh -c 'echo $((1234/3.0))'
411.333333333333333

$ ksh -c 'echo $((12345678901234567890123/3.0))'
4.11522630041152263e+21

Avoid zsh (zcalc has similar problems):

$ zsh -c 'echo $((12345678901234567890123 + 1))'
zsh:1: number truncated after 22 digits: 12345678901234567890123 + 1
-1363962815083169259

I recommend you to avoid expr, it needs weird escapes sometimes:

$ expr 22 \* 333
7326

bc

At the next level is (also POSIX)bc (cousin of RPN dc)

$ echo '22*333' | bc
7326

$ echo '22 333 * p' | dc
7326

The dc was (historically) used to implement bc and got excluded from POSIX in 2017.

Shorter if your shell supports it:

$ bc <<<'22*333'
7326

Or even:

$ <<<'22*333' bc
7326

Both are arbitrary precision calculators with some internal math functions:

$ bc <<<2^200
1606938044258990275541962092341162602522202993782792835301376

$ echo 's(3.1415/2)' | bc -l        # sine function
.99999999892691403749

awk

After those really basic calc tools, you need to go up to other languages

$ awk "BEGIN {print (22*33)/7}"
103.714

$ perl -E "say 22*33/7"
103.714285714286

$ python3 -c "print(22*33/7)"
103.71428571428571

$ php -r 'echo 22*33/7,"\n";'
103.71428571429

function

You may define a function of any of the above options:

c () 
{ 
    local in="$(echo " $*" | sed -e 's/\[/(/g' -e 's/\]/)/g')";
    gawk -M -v PREC=201 -M 'BEGIN {printf("%.60g\n",'"${in-0}"')}' < /dev/null
}

And use:

$ c 22* 33 /7                   # spaces or not, it doesn't matter.
103.714285714285714285714285714285714285714285714285714285714
5
  • dc was never POSIX; this seems to be a common misconception. However, see the Rationale for bc in the 2001 edition of POSIX (pubs.opengroup.org/onlinepubs/9699919799/utilities/…) where it says that standardizing dc was considered, but not done. Also, in the link you gave, dc is listed as a excluded utility, not a removed utility. Mar 6 '20 at 16:06
  • 2
    Another useful tip if you define a function like c() above, is to add "alias calc=noglob c" - that will let you use the asterisk in expressions without quoting it, eg "calc 3*4". Works in zsh, maybe others.
    – Mike B
    Sep 1 '20 at 9:39
  • @isaac: Thank you for the complete answer. I like the function very much! I use it all the time. Could it be that there is not possible to write c 1 * 2? In my console (bash) it returns an syntax error.
    – alex
    Jun 18 at 22:31
  • 1
    Yes, that is not possible as the '*' gets interpreted by the shell and is expanded as a glob to the list of all files in the present working directory. You could quote the * like this (for example): c 1 \* 2 (note the \ used). Or quote the whole string: c '1 * 2' . @alex
    – ImHere
    Jun 18 at 22:38
  • I've wondered about this for years. Sorry I didn't look it up a long time ago. Thanks! Jul 26 at 22:17
26

Reading this pages comments, I see a UNIX/Linux program called calc that does exactly what you want. If on Debian / Ubuntu / derivatives:

sudo apt-get install apcalc

or on Fedora Linux:

sudo dnf install calc

then you can:

calc 236-192

and if you add an alias alias c='calc' to your .bashrc or /etc/bash.bashrc then it just becomes:

c 1+1

on the command line.

1
  • 1
    Not perfect, but good enough for an upvote. Misunderstanding corrected in chat and downvote removed by other user. Deleted my own (inferior) answer... ;-)
    – Fabby
    Nov 6 '18 at 15:41
17

In zsh:

$ autoload zcalc # best in  ~/.zshrc
$ zcalc
1> 1+1
2
2> ^D
$ zcalc 5+5
1> 10
2>
0
10

The units program, whilst not intended to be used as a calculator, actually works fairly well as one.

$ units "236-192"
    Definition: 44
$ 

If there are spaces in the expression, then the expression must be quote-protected.
It supports exponentials and deep nesting of brackets

1
  • 3
    It's versatile: units -t -d 10 "236GB - 192GB" GB outputs 44, units -t -d 15 "236GB - 192GB" bytes outputs 44000000000, etc.
    – agc
    Nov 8 '18 at 4:58
10

Personally, I like libqalculate (the command-line version of Qalculate).

$ qalc
> 236-192

  236 - 192 = 44

While the interface is certainly simple, (lib)qalculate is a powerful, full-fledged calculator. e.g.

> fibonacci(133) to hex

  fibonacci(133) = approx. 0x90540BE2616C26F81F876B9

> 100!

  factorial(100) = approx. 9.3326215E157

> sin(pi)

  sin(pi * radian) = 0

It also does useful things like tab completion, open/close parentheses when necessary, and prints its interpretation of the query.

> 18-2)/4

  (18 - 2) / 4 = 4

To exit, I simply press Ctrl+d.

For even quicker access, set it to something like alias ca='qalc'.

3
  • I read the manual's TOC but couldn'd find anything about CLI. (+1 in the meantime)
    – Fabby
    Nov 6 '18 at 21:54
  • 1
    Thanks @Fabby. I got confused, and the CLI part is actually slightly different. I've updated the answer to clarify.
    – Sparhawk
    Nov 7 '18 at 2:24
  • I wish I could upvote you twice! ;-)
    – Fabby
    Nov 7 '18 at 21:53
7

As remarked in a comment to an earlier reply, the standard shell (ba)sh allows to evaluate arithmetic expressions within $((...)). I could not double-check whether this is part of the POSIX standard, but I did check that it also works on Cygwin and the Mingw32 shell.

To see the result, you'd indeed have to type echo $((...)), which makes some characters more than (interactive use of) bc. However, to use the result in a script, this will most probably be shorter than the bc solution (which could be, e.g., `echo ...|bc`).

Concerning verbosity, the bc command allows the option -q which suppresses output of the "normal GNU bc welcome".

As a final, slightly borderline remark, let's note that bc is not just a calculator but rather a full-fledged programming language (including user defined functions, while & for loops, etc etc). Another fact that suggests to prefer the build-in arithmetic capabilities for such simple calculations, rather than an external program. That said, extracting the data for given partition number(s) and dealing with "M", "G" suffixes, as the original question seemed to ask for, might call for (g)awk rather than bc.

Sources: https://www.gnu.org/software/bc/manual/html_mono/bc.html https://www.gnu.org/software/gawk/manual/html_node/Getting-Started.html

2
  • 1
    Thanks! Excellent first answer! +1
    – Fabby
    Nov 7 '18 at 0:15
  • 3
    $((...)) is called Arithmetic Expansion and it is part of POSIX: pubs.opengroup.org/onlinepubs/9699919799/utilities/… For me the biggest drawback of this feature of a POSIX shell is that it supports only integer arithmetic :(
    – pabouk
    Nov 7 '18 at 9:29
7

What I do in zsh is:

$ <<< $(( 236 - 192 ))
44

In bash, I'd have to explicitly mention cat:

$ cat <<< $(( 236 - 192 ))
44

If I wanted the result to include fractional digits (works in zsh, not in bash), I'd add a radix point to one of the operands

$ <<< $(( 236 / 128 )) 
1
$ <<< $(( 236. / 128 ))
1.84375
10
  • 7
    echo $((236 - 128)) works too ;-). Nov 6 '18 at 18:03
  • Avoid zsh: zsh -c 'print $((12345678901234567890123 + 1))' zsh:1: number truncated after 22 digits: 12345678901234567890123 + 1 -1363962815083169259.
    – ImHere
    Nov 7 '18 at 10:07
  • @Isaac at least zsh tells you it’s truncating; bash just gives you an incorrect answer without complaining. Nov 7 '18 at 14:21
  • @StephenKitt The problem with zsh is more complex than one output shows. Compare: zsh -c 'print $((12345678901234567890123 + 1))' and zsh -c 'print $((123456789012345678901 + 1))'. It is truncating at different lengths and producing different numeric results.
    – ImHere
    Nov 7 '18 at 14:36
  • @StephenKitt Instead Bash is following the manual (and the C language about overflow of a signed int). Not that I personally like it, but it is documented as so. Try bash -c 'echo $((1<<63))' and ``bash -c 'echo $(((1<<63)-1))'`.
    – ImHere
    Nov 7 '18 at 14:40
6

Python open in another tab?

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on 
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 3+3
6
>>>
4
  • Nope, not really, but a neat idea anyway! :-) +1
    – Fabby
    Nov 6 '18 at 22:10
  • powershell can also do the same thing
    – phuclv
    Nov 7 '18 at 5:21
  • 2
    @phuclv yes, but nobody likes PS
    – Dev
    Nov 7 '18 at 12:38
  • 4
    @Dev tons of Unix people love PS
    – phuclv
    Nov 7 '18 at 14:39
4

Have you tried concalc?

Description: console calculator concalc is a calculator for the Linux console. It is just the parser-algorithm of extcalc packed into a simple console program. You can use it if you need a calculator in your shell. concalc is also able to run scripts written in a C-like programming language.

$ concalc 1+1
2
$ concalc sqrt2
1.41421356237309505

Install with:

sudo apt-get install concalc
1
  • 1
    proof... Graag gedaan... :-D
    – Fabby
    May 3 '19 at 19:33
4

Before any of the other brilliant answers were posted, I ended up creating the script /usr/local/bin/c containing:

#!/bin/sh
IFS=' '               # to be on the safe side, some shells fail to reset IFS.
if [ "$#" -eq 0 ];  then
    echo "$(basename "$0"): a (very) simple calculator."
    echo "type $(basename "$0") expression to evaluate (uses bc internally)"
fi

printf '%s\n' "$*" | bc -l  # safe for most shells
                            # we may use 'bc -l <<<"$*"` for ksh, bash, zsh

so: typing c 1+1 yields 2! :-)

Note 1: I used c because that command does not exist on any Unix system that I could find. If you would have aliased that to your c compiler, use anything else that is short and you don't use.
Note 2: Source

1
  • 2
    (1) Decided to use echo "$*" | bc -l as the shebang you used was /bin/sh and I don't know if you have ksh/bash/zsh available. (2) Note that you may change the scale to calculate is you execute `c 'scale=60;777/333', for example. Hope it helps @Fabby
    – ImHere
    Nov 12 '18 at 16:49
2

dc -e '236 192-p'

... of course, if you're not familiar with dc and you require more than subtracting two numbers, you'll spend more time looking up how to use dc (and maybe RPN in general) than you'll save with more familiar methods.

1
  • Yeah, had a 3-minute look at Desk Calculator and knew it wasn't for me: I was a TI, not an HP student.
    – Fabby
    Nov 7 '18 at 22:02
2

If you have gradle installed then you have groovy...

If groovy is pathed correctly you should be able to use:

groovy -e "println 1+1"

This may seem a bit redundant with all the other examples, but:

  • groovy is a powerful language
  • possibly the best library support available
  • powerful and simple math functions (Like arbitrary precision math)
  • uses redirectable stdout for it's output so it is amazingly flexible (great to use inside batch files with backticks `` and the like).

If you don't have java installed it's probably not worth installing groovy & java--it's just an option if groovy is already available.

1
  • Nope, not really, but a neat idea anyway! :-) +1
    – Fabby
    Nov 6 '18 at 22:11
2

Just because Python was mentioned a few times in other answers, here the generalized answer, summarizing the basic idea:

You can use many interpreted languages with a repl as your calculator. This saves you the learning curve for a "special" program, such as bc.

For example if you already happen to know lisp, you could use that as your quick and dirty command line calculator:

sbcl --eval '(progn (print (+ 1 2 3 4)) (quit))'

Or Ocaml, as another example:

echo "let d = 553 - 226 in print_int d" | ocaml -noprompt -stdin

Whatever language deems you most convenient.

1

If python is installed, you can do a lot of mathematical operation through command line. I tried to provide some example below.

I have used python3 you can use python. The difference between python and python3 occur when divided(fractional) operation occur, to avoid the issue see below python vs python3.

Note: Latest all linux dist comes with both Python 2.7 and Python 3.5 by default. In case if require to install python click here.

Add, Subtract, Multiply & Divide:

$ python3 <<< "print(12+3)"
15
$ python3 <<< "print(12-3)"
9
$ python3 <<< "print(12*3)"
36
$ python3 <<< "print(12/3)"
4

Modulus -remainder of the division:

$ python3 <<< "print(14%3)"
2

Floor division:

$ python3 <<< "print(14//3)"
4

Exponent - x to the power of y (x^y):

$ python3 <<< "print(3**2)"
9

Square root (ex: √4 = 2):

$ python3 <<< "print(4**0.5)"
2

More scientific part, you will require import math library. Ex:

The natural logarithm of x = log(x):

$ python3 <<< "import math; print(math.log(4))"
1.386294361119890e6

The base-10 logarithm of x = log10(x):

$ python3 <<< "import math; print(math.log10(10))"
1.0

Factorial (ex: 3! = 3.2.1 = 6):

$ python3 <<< "import math; print(math.factorial(3))"
6

Trigonometry- sin(x), cos(x), tan(x):

$ python3 <<< "import math; print(math.sin(90))"
0.8939966636005579

Fore more math related functions check here.

python Vs python3:

-For divide: (use float):

$ python <<< "print(10.0/3)"
3.33333333333

-instead of

$ python <<< "print(10/3)"
3

Also you can use direct terminal:

$ python3
Python 3.6.8 (default, Jan 14 2019, 11:02:34) 
[GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1+3
4
>>> import math
>>> math.log10(4)
0.6020599913279624
>>> math.sqrt(4)
2.0
>>> 

That's it. Happy coding!

0
1

There are a lot of great answers here, I actually have written a small programming language with this problem in mind, where in typing in the command line ./Ascal 2+2 or ./Ascal "log(10)" you will immediately get the result Final Answer: 4 for 2+2, and I'm sure you can imagine for log base 10 of 10. Just something to keep in mind, it's also a full programming language with a bunch of useful functions built in, plotting in the console, and taking reimann sums of functions you have defined. Check it out the project now comes with a build script so all you need to do is add it to your path variable, or add an alias in your bash config and you have an easy to use calculator!
https://github.com/andrewrubinstein/AscalLang
I'd also be really appreciative of any comments anyone interested enough to check it out might have, hope it can be useful.

1

2020 answer

Append

# Calc
c(){ 
  echo "scale=2; $*" | bc -l
}

to your ~/.aliases, then

$ c 1/3
.33

(The original issue has been solved multiple times already. However, the title "Simple command-line calculator" may require division to some decimal points. The use of the -l option with bc seems to give 20 decimal points, which is perhaps too many for a 'simple' calculator. This answer, which frankensteins answers from @stephenKitt and @sjas was the simplest solution I found.)

1
$ echo $((1+5))
6

This is Bash's Arithmetic Expansion

1

Either bc or qalc.


To automatically have bc always rounding up to two digits: (running it with -l is unwieldy for day to day stuff)

Edit your ~/.bashrc:

alias bc="BC_ENV_ARGS=<(echo "scale=2") \bc"

Open a new shell and run bc and be glad.

1

Use perl / python under the hood.

The advantage?

You get the full power of all math operations

❯ calc 'log(e)'
1.0
❯ calc 'pi*2'
6.283185307179586
❯ calc 'pi**2'
9.869604401089358
❯ calc 'pi**pi'
36.4621596072079

If you stick to string inputs, you don't have to worry about glob expansions of your shell

For zsh or bash have a function something like

function calc {
    python3 -c "from math import *; print(eval($*))"
}

For tcsh add alias something like

alias   Calc            'python3 -c "from math import *; print(eval(\!*))"'
0

Creating a one-liner:

$ c () { echo $(( ${1} )) }

Now you can use simple integer math:

$ c 1+1
2

$ c 25*4
100

$ c 25*4-10
90

$ c 20*5/4
25
3
  • 1
    This is already discussed in Isaac’s answer. Jun 10 '19 at 10:53
  • 1
    @StephenKitt Yes I upvoted Isaac's very detailed answer. I thought a one-liner summarizing some of what he posted would be helpful. The ${1} parameter usage is unique to all answers. Jun 10 '19 at 10:57
  • 3
    I encourage you to look into the reasons other answers don’t use ${1} ;-) Jun 10 '19 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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