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…
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.
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:
Close out your terminal, re-open, and the command should be enabled now.
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:
You’ll need to be in your user folder at the time, which is the default folder anyway for new Terminal window.
open .profile
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.