Does POSIX Prohibit Standalone Use of Relational Operators in bc?

bcposix

I want to compare two numbers with bc. Per this highly rated answer on StackOverflow, I can do it in a manner as such:

printf '%s\n' '1.2 > 0.4' | bc

bc sends 1 to STDOUT, indicating that the statement is true (it would have returned 0 if the statement was false).

Per the POSIX page for bc:

Unlike all other operators, the relational operators ( '<', '>', "<=", ">=", "==", "!=" ) shall be only valid as the object of an if, while, or inside a for statement.

Perhaps I am misinterpreting, but this language seems to disallow the syntax used in the above example.

Is standalone use of relational operators in bc a violation of POSIX? If so, how should I rewrite my example?

Best Answer

Perhaps I am misinterpreting, but this language seems to disallow the syntax used in the above example.

That example assumes GNU bc, which adds its own extensions to the bc language. As documented in its manual, you should use the -s switch to make it process the exact POSIX bc language, or the -w switch if you want it to warn about extensions:

$ echo '1.2 > 0.4' | bc -s
(standard_in) 2: Error: comparison in expression
$ echo '1.2 > 0.4' | bc -w
(standard_in) 2: (Warning) comparison in expression
1
$ echo '1.2 > 0.4' | bc
1

If so, how should I rewrite my example?

$ printf 'if(%s > %s){a=1};a\n' 1.2 0.4 | bc -s
1

thanks @icarus for the shorter, easier on the eyes version.

Related Question