![]() |
![]()
| ![]() |
![]()
NAMEgexpr - handy shell calculatorSYNOPSISgexpr [ options ] expressionDESCRIPTIONgexpr is an expression parser that can be used as a simple command-line calculator, as in gexpr 'sin(pi/4)*sqrt(4)', or to add floating point math to shell scripts. It is meant to be an alternative to bc (1), being less powerful but lighter and much more intuitive. It also provides a few nice features of its own.If an expression is given as argument, it must be protected from the shell using quotes as in the example above. If you fail to do so, parentheses will be interpreted and the * character will be expanded by the shell, wreaking havoc. Using double quotes " " is necessary if you want to use shell variables within expression. gexpr supports the usual arithmetical operators + - * / , the relational operators < <= > >= == != , and all the standard C mathematical functions apart from frexp (3) and modf (3), which cannot be fully implemented since they actually return two values. In addition, gexpr provides the constants defined in math.h (M_PI, etc), the fact(n) function, which returns the factorial of n, and the rnd(n) function, which returns a random number between 0 and n. A nice feature of gexpr is the possibility of using other bases than 10. For instance, this expression is allowed: $ gexpr "0x10 + 0b1010 + 010"
the prefix "0x" denotes numbers written in base 16, "0b" numbers in base 2, and "0" octal numbers. The command "base nn" is used to display the results in a base between 2 and 16. Example: gexpr> base 16
The command "decimals nn" (or "dec nn") specifies the number of decimal positions. Example: gexpr> PI
COMMANDS
OPTIONS
EXAMPLESgexpr 2 + 10 / 2gexpr "sqrt(5) < log(10)" echo "sqrt(2)/2" | gexpr -n gexpr "sin($X) - tan($Y)" gexpr "$X + ($Y)*log10(${ZZ})" This is an interesting use of gexpr in a shell script: #!/bin/sh DEC=`echo "M_PI_2" | gexpr -n` EXA=`echo "M_PI_2" | gexpr -n -b16` echo "Pi/2 is $DEC (or $EXA in hexa)" Another example: #!/bin/sh
BUGSIt is awfully slow and its use cannot replace a "real" programming language supporting floating point math.Most errors are trapped but some are not, like overflows and underflows. For example, on the Linux box it was written on gexpr overflows when the result exceeds about 1.797e+308. It would be nice to add command-line editing. This would make gexpr quite bigger, though. AUTHORGuido Gonzato <ggonza@tin.it>SEE ALSOexpr (1), sh (1), bc (1)
|