logoalt Hacker News

linkregisteryesterday at 9:45 PM2 repliesview on HN

It's POSIX convention to write to stderr for anything that's not strict program output. I have seen 2>&1 far too often in scripts. I don't worry about it and happily write error messages to stderr whenever my scripts exit without a 0 status code.


Replies

ryandrakeyesterday at 10:33 PM

Another thing that gets screwed up a lot is: Comand line usage help/information should be printed to stderr if it was invoked because the user passed an invalid option to the command line (in other words, the usage text counts as diagnostic[1] info), but it should be printed to stdout if the user invoked the application with -h, --help or similar. Reasons:

1. If you mess up the command line to the program in a script or pipe, and get a bunch of usage output in stdout, a downstream consumer of that stdout might think its legit program output and try to parse it.

2. If your user actually calls the program with -h or --help, they might want to |less through it to read it on a small terminal screen. Output that to stdout.

3. Generally, you can always tell if something is going wrong by grepping for errors or warnings a single stream (stderr), or by looking for a nonzero exit code.

But your general principle applies: Output expected by the user -> stdout. Diagnostic output or output incidental to the program's operation or errors -> stderr.

1: https://pubs.opengroup.org/onlinepubs/9799919799/functions/s...

show 2 replies