Should I output warnings to STDERR or STDOUT?

柔情痞子 提交于 2019-11-30 00:02:03

If I saved 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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!