Bug 234430 - bc(1) writes error messages to standard output instead of standard error
Summary: bc(1) writes error messages to standard output instead of standard error
Status: In Progress
Alias: None
Product: Base System
Classification: Unclassified
Component: bin (show other bugs)
Version: 12.0-STABLE
Hardware: Any Any
: --- Affects Some People
Assignee: freebsd-bugs mailing list
Depends on:
Reported: 2018-12-26 23:46 UTC by Martijn Dekker
Modified: 2019-01-12 12:37 UTC (History)
2 users (show)

See Also:


Note You need to log in before you can comment on or make changes to this bug.
Description Martijn Dekker 2018-12-26 23:46:37 UTC
Upon encountering a parsing error, bc(1) passes an error message on to
dc(1), which writes the error message to standard output along with the
normal output.

That is a bug. Error messages should go to standard error instead, as
POSIX specifies:

GNU 'bc', Solaris 'bc', and (as of 2017) OpenBSD 'bc' act like POSIX says and write error messages to standard error.

Bizarrely, the exit status of bc(1) is left unspecified:
And indeed, all versions of 'bc' exit with status 0 if there is an input
error such as a parsing error, so the exit status cannot be used to
catch it. That leaves examining standard error as the only method for a
program calling bc(1), such as a shell script, to distinguish between an
error state and normal operation. That is, with this bug, there is no
way at all.

The following example shell function transparently hardens bc(1) by
intercepting standard error and exiting the program or subshell if an
error was produced.

bc() {
	_bc_err=$(command -p bc "$@" 2>&1 1>&3)
	[ -z "${_bc_err}" ] && return
	printf '%s\n' "$0: bc(1) caught errors:" "${_bc_err}" 1>&2
	exit 127
} 3>&1

This bug was fixed on OpenBSD 'bc' back in Feburary 2017. I figured FreeBSD would eventually pull in that fix since FreeBSD 'bc' is based on OpenBSD 'bc', but as of FreeBSD 12.0 that hasn't happened.

The OpenBSD patch that fixes the bug is here:
Comment 1 commit-hook freebsd_committer 2019-01-12 12:35:06 UTC
A commit references this bug:

Author: nyan
Date: Sat Jan 12 12:35:02 UTC 2019
New revision: 342964
URL: https://svnweb.freebsd.org/changeset/base/342964

  Sync with OpenBSD.

  bc.y: Rev 1.50
  - write parse errors to stderr, prompted by Martijn Dekker
  - we're only interactive if stdout en stderr are a tty as well as stdin

  PR:		234430
  Obtained from:	OpenBSD
  MFC after:	1 week