linuxshellbcdc

Is there a good tool to parse/evaluate mathematical expressions?


Argghh:

$ echo 2 4 | bc
(standard_in) 1: parse error
$ echo $?
0

Why on earth would an otherwise perfectly reasonable program succeed when it recognizes a parse error? Clearly, I cannot use bc to evaluate an expression. Personally, I like dc, but my users do not want reverse polish. Given an arithmetic expression of the form that bc recognizes, is there a reasonable program for evaluating the result? Or is there a way to make bc reasonable? (Here, "reasonable" means that it fails when the input is bogus.)


Solution

  • bc will try to recover from errors, and keep processing later statements. For example:

    $ echo "2 + 3; 
        4 4;
        3 + 4" | bc
    5
    (standard_in) 2: parse error
    7
    

    Thus, it's not clear if it should return an error in that case. It successfully parsed and processed the input, correctly recovering from the error and continuing to process later instructions. According to POSIX, the behavior of bc is undefined when invalid input is detected in non-interactive mode, so this is within the specification of how bc should behave.

    If you want to test if there were any errors while processing your input, you can redirect stderr to a temporary file, and then check the contents of that to look for errors:

    bcerr=$(mktemp -t bcerr)
    result=$(echo 2 4 | bc 2>$bcerr)
    if test -s $bcerr
    then
      # handle errors
    else 
      # handle success
    fi
    rm $bcerr