Work the Shell - Solve: a Command-Line Calculator Redux

February 1st, 2008 by Dave Taylor in

Dave completes his explanation of writing a helpful interactive command-line calculator as a shell script.
Your rating: None Average: 4.5 (2 votes)

Ooops! Two months ago, I started exploring how you can write a simple but quite helpful interactive command-line calculator as a shell script and ended the column with “Next month, we'll dig into useful refinements and make it a full-blown addition to our Linux toolkit. See you then!”

Unfortunately, last month, I got sidetracked with the movie The Number 23 and started another script looking at how to do numerology within the shell scripting environment. You'd think I was a typical programmer or something, being sidetracked and losing a thread by picking up another one. It reminds me of those glorious startup days from the late 1990s too, but that's an entirely different story.

Anyway, numerology can wait another month. This column, I'd like to complete the command-line calculator because, well, because it's so darn useful and simultaneously astonishing that there isn't a decent command-line calculator in Linux after all these years. I mean, really!

When Last We Met

It was a while back, so let me remind you that the wicked short script to give you the rudimentary calculator is this:


#!/bin/sh

bc << EOF
scale=4
$@
quit
EOF

That's it. Name it solve.sh, for example, and you can test it, as shown here:

$ sh solve.sh 1+3
4
$ sh solve.sh 11/7
1.5714

It's easy enough to alias solve to the shell command too:

alias solve="sh solve.sh"

Or, better:

alias solve="sh ~/bin/solve.sh"

As that'll work regardless of where you are in the filesystem (location-dependent commands are a typical shell gaffe).

What I'd really like, however, is to be able to go into a “solve” mode where anything I type automatically is assumed to be a mathematical equation, rather than have to type solve each time.

Rapping about Wrappers

We've talked about shell script wrappers in the past, so you should recall this basic structure:

while read userinput
do
  echo "you entered $userinput"
done

That's too crude to use as of yet, but we easily can add a prompt so that it looks like a real program:

echo -n "solve"
while read expression
do
  echo "you entered $expression"
  echo -n "solve: "
done

Look good? Actually, it's not. There's a subtle error here, one that's another common scripting mistake. The problem is that there are two echo commands in Linux: one that's the built-in capability of the shell itself, and one that's a separate command located in /bin. This is important because the built-in echo doesn't know what the -n flag does, but the /bin/echo command does. A tiny tweak, and we're ready to test it:

/bin/echo -n "solve: "

while read expression
do
  echo "you entered $expression"
  /bin/echo -n "solve: "
done

Let's see what happens:

solve: 1+1
you entered 1+1
solve: ^D

That's more like it.

What we really want though, is a script that's smart enough to recognize whether you've specified parameters on the command line. If you have, it solves that equation, and if you haven't, it drops you into the interactive mode.

That's surprisingly easy to accomplish by testing the $# variable, which indicates how many arguments are given to the script. Want to see if it's greater than zero? Do this:

if [ $# -gt 0 ] ; then

One more refinement before I show you the script in its entirety: I want to have it quit if users type in quit or exit, rather than force them to type ^D to indicate end of file on standard input (which causes the read statement to return false and the loop to end).

This is done with a simple string comparison test, which you'll recall is done with = (the -eq test is for numeric values). So, testing $expression to see whether it is “quit” is easy:

if [ $expression = "quit" ] ; then

To make it a bit more bulletproof, it's actually better here to quote the variable name, so that if users enter a null string (simply press Return), the conditional test won't fail with an ugly error message:

if [ "$expression" = "quit" ] ; then

Because I like to make my scripts flexible, I've also added exit as an alternative to quit, which easily is done with a slightly more complicated conditional test:

if [ "$expression" = "quit" -o
     "$expression" = "exit" ] ; then

The -o is the logical OR statement in a shell conditional test, but I have a feeling you've already figured that out.

The Full Script

Here's where the script stands at this point, in its entirety:


#!/bin/sh

if [ $# -gt 0 ] ; then
bc << EOF
scale=4
$@
quit
EOF
else
  /bin/echo -n "solve: "

  while read expression
  do
    if [ "$expression" = "quit" -o 
         "$expression" = "exit" ] ; then
      exit 0
    fi
bc << EOF
scale=4
$expression
quit
EOF
    /bin/echo -n "solve: "
  done

  echo ""
  echo "solved."
fi

exit 0

Neat and darn useful, I'd say. If I were to continue hacking on it, the next thing I would do is write a simple help page that I'd store in some library folder and display on entry of ? or help. It simply would explain the syntax of the expressions understood by bc (though as we're invoking bc iteratively, we can't have persistent variables and so forth, so unfortunately, this approach won't let us access the full power of the binary calculator).

To learn what type of sophisticated expressions you can enter, simply type man bc. Then, let that be your inspiration for further tweaks and mods to this script!

Next month, I'll go back to the numerology script and see what strange things we can ascertain about the apparently benign world around us. Remember, just because I got out of sequence, doesn't mean we're not out to get you, dear reader!

Dave Taylor is a 26-year veteran of UNIX, creator of The Elm Mail System, and most recently author of both the best-selling Wicked Cool Shell Scripts and Teach Yourself Unix in 24 Hours, among his 16 technical books. His main Web site is at www.intuitive.com, and he also offers up tech support at AskDaveTaylor.com.

__________________________


Special Magazine Offer -- Free Gift with Subscription
Receive a free digital copy of Linux Journal's System Administration Special Edition as well as instant online access to current and past issues. CLICK HERE for offer

Linux Journal: delivering readers the advice and inspiration they need to get the most out of their Linux systems since 1994.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
Mike 2009's picture

I use this great command

On January 29th, 2009 Mike 2009 (not verified) says:

I use this great command line calculator

http://www.fnoware.st/?CLC-linux

There is a windows version also that I use on my windows computer

Post new comment

Please note that comments may not appear immediately, so there is no need to repost your comment.
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd> <i> <b>
  • Lines and paragraphs break automatically.

More information about formatting options

Newsletter

Each week Linux Journal editors will tell you what's hot in the world of Linux. You will receive late breaking news, technical tips and tricks, and links to in-depth stories featured on www.linuxjournal.com.
Sign up for our Email Newsletter

Tech Tip Videos

From the Magazine

December 2009, #188

If last month's Infrastrucuture issue was too "big" for you then try on this month's Embedded issue. Find out how to use Player for programming mobile robots, build a humidity controller for your root cellar, find out how to reduce the boot time of your embedded system, and if you're new to embedded systems find out the basics that go into one. You can also read about the Beagle Board, the Mesh Potato and a spate of other interestingly named items. And along with our regular columns don't miss our new monthly column: Economy Size Geek.


Read this issue