Creating a Command-Line Calculator

Problem

You need more than just integer arithmetic, and you’ve never been very fond of RPN notation. How about a different approach to a command-line calculator?

Solution

Create a trivial command-line calculator using awk’s built-in floating-point arithmetic expressions:

# cookbook filename: func_calc

# Trivial command line calculator
function calc
{
    awk "BEGIN {print "The answer is: " $* }";
}

Discussion

You may be tempted to try echo The answer is: $(( $* )), which will work fine for integers, but will truncate the results of floating-point operations.

We use a function because aliases do not allow the use of arguments.

You will probably want to add this function to your global /etc/bashrc or local ~/.bashrc.

The operators are what you’d expect and are the same as in C:

$ calc 2 + 3 + 4
The answer is: 9

$ calc 2 + 3 + 4.5
The answer is: 9.5

Watch out for shell meta characters. For example:

$ calc (2+2-3)*4
-bash: syntax error near unexpected token `2+2-3'

You need to escape the special meaning of the parentheses. You can put the expression inside single quotes, or just use the backslash in front of any special (to the shell) character to escape its meaning. For example:

$ calc '(2+2-3)*4'
The answer is: 4

$ calc (2+2-3)*4
The answer is: 4

$ calc '(2+2-3)*4.5'
The answer is: 4.5

We need to escape the multiplication symbol too, since that has special meaning to bash as the wildcard for filenames. This is especially true if you like to put whitespace around your operators, as in 17 + 3 * 21, because then * will match all the files in the current directory, putting their names on the command line in place of the asterisk—definitely not what you want.

See Also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.70.101