On , I learnt ...

When to use stdout and stderr in shell scripts

I recently gained a deeper understanding of when to use stdout and stderr in shell scripts. The definitions in Wikipedia are:

Standard output (stdout):

Standard output is a stream to which a program writes its output data.

Standard error (stderr):

Standard error is another output stream typically used by programs to output error messages or diagnostics. It is a stream independent of standard output and can be redirected separately.

I had been following these guidelines but was missing some subtleties.

Write --help output to stdout

When you run:

> $command --help 

you’re explicitly asking for help so the output should be written to stdout; the help output is the data.

This is documented in the GNU coding standards and discussed in this Hacker News thread.

However, if you include the --help content or usage instructions in an error message, then it should be written to stderr. E.g. if you run:

> $command --bad-option 

then the error message should be written to stderr instead.