SEARCH

How-To Geek

Create Your Own Quick Calculator Function for the Terminal

If you’re anything like me, you’ve always got a Terminal window open, and you probably have even assigned a hotkey to bring it up anytime. So why open up the boring calculator when you can solve equations right there on the command line?

This is a simple method for creating a calculator using the built-in function support in the Bash shell. Essentially all we’re doing is assigning the question mark to run the bc command with whatever arguments you type after it.

Creating the Terminal Calculator Function

To create the function, just paste in the following command into the Terminal…

? () { echo "$*" | bc -l; }

Now you can use it by simply typing a ? and then the math equation you want solved. If you’re going to use spaces, you should surround it in quotes, otherwise you’ll get an error like this:

You can also use it on Windows if you have Cygwin installed—you’ll need to make sure you’ve installed the bc package, of course.

image

Since this is using the bc command, it’s pretty powerful.

Making the Function Save Across Restarts

If you’re using Linux or Cygwin under Windows, you’ll want to edit the following file and put the line at the bottom:

vi ~/.bash_profile

Close out your terminal, re-open, and the command should be enabled now.

image

Saving the Function in OS X

If you’re using OS X, you’ll need to go another route, at least in my testing—first, open up a Terminal, and then type in the following commands:

touch .profile

open .profile

You’ll need to be in your user folder at the time, which is the default folder anyway for  new Terminal window.

The open command will open up the new .profile file in Textedit, where you can paste in the line, save, and close.

Close out the Terminal, re-open it, and you should have the function available.

Lowell Heddings, better known online as the How-To Geek, spends all his free time bringing you fresh geekery on a daily basis. You can follow him on if you'd like.

  • Published 02/3/11

Comments (7)

  1. StevenTorrey

    Or just use the calculator that microsoft now offers free. And simple. Did I say simple?

  2. Karthik

    In Windows command prompt, arithmetic calculations can be achieved through the “set” command with “/a” option.
    However, it is not very powerful. It does not support floating point calculations.

  3. ProstheticHead

    Now I know how to ‘Geek’.

  4. Todd

    My favorite command line calculator: Python

  5. Krikor

    Hehehe. The point is not the calculator the point is to look smart and feel smart.

  6. `gene

    Why ‘?’ assigning this to ‘=’ makes a lot more sense.

  7. 7eggert

    If you don’t need floating points:

    echo $((1+4/2))

Get Free Articles in Your Inbox!

Join 134,000 newsletter readers

Email:

Go check your email!