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?

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

1 2 3 4 5 6 7 |
# cookbook filename: func_calc # Trivial command line calculator function calc { awk "BEGIN {print \"The answer is: \" $* }"; } |

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:

1 2 3 4 5 |
$ 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:

1 2 |
$ 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:

1 2 3 4 5 6 7 8 |
$ 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.