Stuart P. Bentley
Stuart P. Bentley

Reputation: 10755

Should I output warnings to STDERR or STDOUT?

I'm making a script that handles a predefined set of data, outputting to a file. I want to pop up a warning when one datum (which is always "Regular" in every set that I've had access to) is different stating that this value is unhandled (since I don't know how it affects the data). Should I output this warning to stderr or stdout?

Upvotes: 42

Views: 13042

Answers (3)

Mark Rushakoff
Mark Rushakoff

Reputation: 258478

If I save the output of this script (i.e. stdout only) so that I could process it later, would that warning interfere with how the output is parsed? Moreover, if output is piped to another process, the warning should show up on the terminal, so the user sees it immediately.

For those reasons, in general, you output warnings to stderr.

Upvotes: 45

Michael Berg
Michael Berg

Reputation: 453

The warning should go to stderr.

In addition to the points presented by others (causing parsing errors for downstream processes and hiding the error from the user at the console), there is an issue of flexibility.

If the user does not want the warning from stderr to go to a downstream process that is parsing stdout, they don't have to do anything special.

your_script | downstream_process

If the user wants the warning from stderr to go to a downstream process that will parse stdout and stderr, the user can use 2>&1 to redirect stderr into stdout.

your_script 2>&1 | downstream_process

If you output both warnings and any normal data to stdout, the user has no good way of separating the warnings from the data without parsing everything. So sending the warnings to stderr gives your script more flexibility as well.

Upvotes: 13

Martin
Martin

Reputation: 3753

The real question is: if someone were to redirect the output of your script to a file, would you want the warning placed in the file, or directed to the user?

If you're expecting the user to take some action as a result of the warning, it should go to STDERR. If some downstream script is likely to be tripped up by the warning, it should go to STDERR.

Upvotes: 3

Related Questions