Simple command-line calculator

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 "%sn" "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="290d69">[email protected]</a>" | 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.

Method 2

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("%.60gn",'"${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("%.60gn",'"${in-0}"')}' < /dev/null
}

And use:

$ c 22* 33 /7                   # spaces or not, it doesn't matter.
103.714285714285714285714285714285714285714285714285714285714

Method 3

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.

Method 4

In zsh:

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

Method 5

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

Method 6

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

Method 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

Method 8

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

Method 9

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

Method 10

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

Method 11

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 '%sn' "$*" | 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

Method 12

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.

Method 13

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.

Method 14

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.

Method 15

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

Method 16

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!

Method 17

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.

Method 18

$ echo $((1+5))
6

This is Bash’s Arithmetic Expansion

Method 19

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.

Method 20

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(!*))"'

Method 21

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x