An awkward awker

A command-line calculator

For simple calculation such as "46 times 365.25 times 86400", many people use pocket calculators. (They are still called dentaku in Japanese, literally "electric desks", but surely an abbreviation of "electronic desktop calculators".) I do not like their small key tops. I prefer the "full" keyboard (not even the numerical keypad) of a computer.

But I find that the Unix shell ("tcsh" in my case) does not support much calculation. Some textbooks of Unix recommends the "bc" command. My Linux system does have it, and it seems to be easy to use. But I already have learned how to calculate in Awk. When I want an answer quickly, I want to use the syntax I have already been accustomed.

I simply invoked "awk", and found some messages introducing how to use it. Then I tried the simplest Awk program, leaving its standard input at the console, and keyed in the formula. But it just echoed its input.

% awk '{print}'
3*4
3*4
100+1
100+1
control-D
%

A variant behaved similarly.

% awk '{print $1}'
3*4
3*4
100+1
100+1
control-D
%

The usual way to force Awk evaluate numerical values of a formula yielded a situation somewhat worse for me.

% awk '{print $1+0}' 
3*4
3
100+1
100
control-D
%

At last, I arrived at an idea to write a shell script that invokes awk. I call it "ev", as an even shorter abbreviation of "evaluate" than "eval". (My shell already has a built-in function called "eval", but it is not useful for my purpose.) If it is put in the command path, it works like this:

% ev "3*4"
12
% ev "46*365.25*86400"
1451649600
%

Note that such characters as asterisks and parentheses must be quoted by (double or single) quotation marks. Otherwise they are interpreted by the shell. For example,

% ev 3*4
ev: No match.
%

It just means that there is no file whose name begins with "3" and ends with "4" in the current directory.

The source code is here [ev.csh]. The trick is to give a formula to the interpreter as a part of a program rather than input data. As easily seen from the source code, any formula that can be the first argument of "print" in Awk can be given from the command line. Built-in functions of the Awk interpreter can be used, as:

% ev "sqrt(9)"
3
%

Here, the input file to awk is explicit nothing ("/dev/null"), and all the job is done in the BEGIN section. This is a typical example of what I call "awkward" usage of Awk, but it works.


2004-Jan-29; minor revision 2004-Jul-03, 2015-Jun-14
MASUDA Kooiti

[To the index page of "an awkward awker"] [To the entrance page of K. Masuda in English]