Work the Shell - Solve: a Command-Line Calculator Redux
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!
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.
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.
Dave Taylor has been hacking shell scripts for over thirty years. Really. He's the author of the popular "Wicked Cool Shell Scripts" and can be found on Twitter as @DaveTaylor and more generally at www.DaveTaylorOnline.com.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- A Topic for Discussion - Open Source Feature-Richness?
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Home, My Backup Data Center
- What's the tweeting protocol?
- Readers' Choice Awards
- New Products
- RSS Feeds
- Dart: a New Web Programming Experience
- Reply to comment | Linux Journal
9 hours 58 min ago - Reply to comment | Linux Journal
12 hours 30 min ago - Reply to comment | Linux Journal
13 hours 47 min ago - great post
14 hours 22 min ago - Google Docs
14 hours 45 min ago - Reply to comment | Linux Journal
19 hours 33 min ago - Reply to comment | Linux Journal
20 hours 20 min ago - Web Hosting IQ
21 hours 54 min ago - Thanks for taking the time to
23 hours 30 min ago - Linux is good
1 day 1 hour ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




Comments
I use this great command
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