Any Command Line Calculator for Ubuntu?

Any Command Line Calculator for Ubuntu?

I am looking for a calculator which can do calculations in the terminal itself, without any other extra prefixes and suffixes.

For example: If I typed something like 10000-9000 in the terminal, the answer should come out as 1000.

Once again I am saying, I just need a quick calculator in the terminal, without any characters added. I know if I switch to Python, it can do that, but I don't want it in such a way.

10

25 Answers

You can use calc. Is not installed by default, but you can install it quickly using the following command:

sudo apt-get install apcalc

After you have installed, you can do any calculation do you wish:

$ calc 5+2
    7
$ calc 5-2
    3
$ calc 5*2          
    10
$ calc 5/2
    2.5
$ calc 5^2
    25
$ calc 'sqrt(2)' 
    1.4142135623730950488
$ calc 'sin(2)'
    0.9092974268256816954
$ calc 'cos(2)'
    -0.416146836547142387
$ calc 'log(2)'
    ~0.30102999566398119521
$ calc 'sqrt(sin(cos(log(2))))^2'
    ~0.81633199125847958126
$ # and so on...

For more information , view its man-page

5

You can do simple integer arithmetic natively in bash using the ((...)) syntax, e.g.

$ echo $((10000-9000))
1000

There is also the bc calculator, which can accept arithmetic expressions on standard input

$ echo "10000-9000" | bc
1000

The bc program can do floating point arithmetic as well

$ echo "scale = 3; 0.1-0.09" | bc
.01
9

Bash Arithmetic

Another possible solution is to add a simple function for Bash's built-in arithmetic. Put this in your .bashrc file to try it out:

=() {
    echo "$(($@))"
}

So now, you don't even need $((...)) anymore, just = which seems natural enough.

Replacement

Another thing if you want to be even faster: you can make it replace p with + and x with *. This will work for that:

=() {
    local IFS=' '
    local calc="${*//p/+}"
    calc="${calc//x/*}"
    echo "$(($calc))"
}

= 5 x 5  # Returns 25
= 50p25  # Returns 75

Now you don't even need Shift anymore, the only thing is =  in front of arithmetic.

Hexadecimal output

Output can be displayed in both decimal and hexadecimal, if so desired. (Note: using x substitution will conflict with the 0x... hex syntax)

=() {
    local answer="$(($@))"
    printf '%d (%#x)\n' "$answer" "$answer"
}

Example:

$ = 16 + 0x10
272 (0x110)

$ = 16**3 + 16**4
69632 (0x11000)
Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.