Command-line Calculators

From LinuxReviews
Jump to navigationJump to search

Here's the basics of the calculators you (probably) have installed.

bash[edit | edit source]

bash has math built into it. The trick is to do echo $((x+y)) as in:

echo $((2+2)) will output 4 and

echo $((8*8/2+200)) will output 232.

BCMM provided this information.

Perl[edit | edit source]

perl is a programming language. The -e option can be used from the command-line to execute code. print will print out variables and also sums if you feed it numbers and/or equations.

perl -e "print 2+2"

will produce the answer 4 and

perl -e "print 8*8/2+200"

will correctly output 232.

Append ;echo if you want a newline after your output - perl will by default not add a newline. For example, perl -e "print (3010*2212)/987";echo outputs 6658120 and adds a newline after the answer.

bc[edit | edit source]

Bc-howto-fs8.png

bc is described in it's manual page as "an arbitrary precision calculator language".

bc can be used to quickly do simple calculations in a terminal. The trick is to pipe numbers and equations to it. As an example,

echo 2+2|bc will output 4 and echo 8*8/2+200|bc will output 232.

bc can do very advanced math. You will have to read the manual page to use it as a scientific calculator. A graphical calculator like SpeedCrunch really is a better choice if that is your use-case.

Regardless, if you want to do math in shell-scripts and things like that you can do it with bc.

For example, of you run

pi=$(echo "scale=10; 4*a(1)" | bc -l)

in a script you get to use the correct value for $pi - echo $pi will then produce 3.1415926532. Do notice how bc accepts $scale, you can use it to calculate PI with 20 or 100 digits.

expr[edit | edit source]

expr will, according the fine manual, "evaluate expressions". However, they need to be separated by spaces and they can't have quotes around them. Thus, expr 2+2 will output 2+2 while expr 2 + 2 will output 4.

Further, expr "8 * 8" will output "8 * 8" while expr 8 "*" 8 produces 64

expr is just not a good option since you can only do two arguments.

honorable mentions[edit | edit source]

The IRC client IRC has a built-in /calc command which, under the hood, is a simple irssi alias for:

EXEC - if command -v bc >/dev/null 2>&1\; then printf '%s=' '$*'\; echo '$*' | bc -l\; else echo bc was not found\; fi

So you can do math with irssi - but you're really just doing it with bc


Add your comment
LinuxReviews welcomes all comments. If you do not want to be anonymous, register or log in. It is free.