35

Should the usage message which is printed with e.g.

 command -?

of a Unix command go to stderr or stdout, and why? Should it go to the same place if the user makes a mistake with an option?

  • 5
    Additional note: don't use -? use --help and -h

    Because --help and -h are standard and because -? will can be interpreted by the shell.

    – ctrl-alt-delor Mar 08 '11 at 09:53
  • 1
    @richard This is an excellent point. Fun trick (in bash): touch -- -l; ls -? — you actually get a long listing as if you'd passed -l to ls. – mattdm Mar 08 '11 at 12:56
  • @richard. When you don't know whether the command accept GNU-style long options or may support a -h option for other thing than a help message, then '-?' (with the quotes) or -: give you a good chance to get an error (and usage) message since : and ? can't be valid options for anything using getopt(3). – Stéphane Chazelas Feb 08 '13 at 22:40
  • @Stephane Chazelas. If I understand your comment correctly, you are writing from the perspective of a user of a program, this question I think is from the perspective of someone writing a program. – ctrl-alt-delor Feb 09 '13 at 11:55

1 Answers1

61

It should go to stdout, so you can type:

command --help | less

This is also recommended by the Gnu Coding Standards on --help.

On the other hand, the usage message that you get when you use an invalid option or omit a required argument should go to stderr, because it's an error message, and you don't want it to feed into the next command in a pipeline.

When you use --help, the usage message is the normal and expected output of the command. Therefore, it goes to stdout, so it can be piped to another command, like less or grep.

When you say command --bogus-option | other-command, you don't want the usage message going to stdout, because it's now unexpected output that should not be processed by other-command. Also, if the output of --help is more than a handful of lines, then the usage error message should only contain a summary of the --help output, and refer the user to --help for additional details.

cjm
  • 27,160
  • 1
    It's a bit confusing to have two different output streams for the same message depending on something isn't it? –  Mar 08 '11 at 08:05
  • 8
    Perhaps, but they're not necessarily the same message. If the output of --help is more than a few lines, then the usage message produced by an invalid option should be just a short summary saying to use --help to see the complete information. – cjm Mar 08 '11 at 08:38
  • 6
    +1 - this is 100% correct, and I don't see any room for disagreement here. – simon Mar 08 '11 at 10:04
  • 1
    Is it safe to assume one should do likewise with the command's exit status? eg 0 if --help was explicitly asked for, otherwise >0. – ibonyun Nov 27 '23 at 20:42