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.

  • 3
    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 at 19:53
  • 1
    dc is (IMO) far superior to bc. – William Pursell Nov 6 at 22:53
  • 1
    I think the unallocated space between ptn 3 and 5 should be 236 - 192, and not 236 - 128? – Digital Trauma Nov 6 at 23:02
  • @DigitalTrauma good eye! (It was just an example and no one spotted that one!) – Fabby Nov 7 at 0:10
  • Do you, by "simplest", in fact mean a calculator that allows you to type the absolute least? This is what it seems like in your comparison of bc and expr. In that case you may want an RPN calculator like dc. – Kusalananda Nov 7 at 6:39

12 Answers 12

up vote 22 down vote accepted

You can greatly 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 }
$ c 1+1
2

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

  • 1
    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 at 16:24
  • Right, it’s more about verbosity ;-). – Stephen Kitt Nov 6 at 16:26
  • 1
    @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 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.) – Olivier Dulac Nov 7 at 14:03
  • Rather use bc -l in the function definition to make it more capable. – Isaac Nov 10 at 3:48

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

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
    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 at 15:41

In zsh:

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

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

  • 2
    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 at 4:58

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 POSIX but got removed 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
  • Holy moly! +1 I have what I need now though: c 1+1 (for 'Calculate') ;-) – Fabby Nov 7 at 22:01

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
  • 6
    echo $((236 - 128)) works too ;-). – Stephen Kitt Nov 6 at 18:03
  • Avoid zsh: zsh -c 'print $((12345678901234567890123 + 1))' zsh:1: number truncated after 22 digits: 12345678901234567890123 + 1 -1363962815083169259. – Isaac Nov 7 at 10:07
  • @Isaac at least zsh tells you it’s truncating; bash just gives you an incorrect answer without complaining. – Stephen Kitt Nov 7 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. – Isaac Nov 7 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))'`. – Isaac Nov 7 at 14:40

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

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

$ qalc
> 236-192

  236 - 192 = 44

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

  • I read the manual's TOC but couldn'd find anything about CLI. (+1 in the meantime) – Fabby Nov 6 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 at 2:24
  • I wish I could upvote you twice! ;-) – Fabby Nov 7 at 21:53

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
>>>
  • Nope, not really, but a neat idea anyway! :-) +1 – Fabby Nov 6 at 22:10
  • powershell can also do the same thing – phuclv Nov 7 at 5:21
  • 1
    @phuclv yes, but nobody likes PS – Dev Nov 7 at 12:38
  • 1
    @Dev tons of Unix people love PS – phuclv Nov 7 at 14:39

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.

  • 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 at 22:02

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.

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

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

  • I see a downvote, but no explanation. What's so bad about this solution? – Fabby Nov 6 at 15:18
  • For I see no logic in not using bc directly. Furthermore, what does your script provide to the user? I see you are a member for 4 years, but I am sorry for my inability to see it. If you explain it, I will upvote maybe. – Vlastimil Nov 6 at 15:22
  • @Vlastimil Please see me in chat? – Fabby Nov 6 at 15:26
  • Undeleted after allowing more experienced people to answer. – Fabby Nov 8 at 10:43
  • 1
    (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 – Isaac Nov 12 at 16:49

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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