3 ms·
I find this construct quite interesting.... help_msg() { >&$1 echo "Usage: $0 [file.c... >&$1 echo "Execute C progams from the command line."
by cnvogel 12y ago
I find this construct quite interesting....
help_msg() {
>&$1 echo "Usage: $0 [file.c...
>&$1 echo "Execute C progams from the command line."
...
}
for that it puts the redirection at the beginning of the line, which is unusual and I didn't even realize until now that it's valid. ( example: >&55 redirects stdout to filescriptor number 55, and here >&$1 redirects stdout of echo to the filedescriptor number given as the first argument to the function)
# help if we have no arguments and no stdin
if [ $# -eq 0 ] && [ -t 0 ]; then
help_msg 2 # <--- NOTE 2 = stderr
exit 1
fi
# help if we get the flags
if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then
help_msg 1 - <--- NOTE 1 = stdout
exit 0
fi
And second, that the author seems to switch between outputting the help_msg on stdout or stderr, depending on if stdout exists. I always was under the impression that only the actual script result ought to go to stdout, and personally I always put out general debugging, error messages, but also the usage, unconditionally to stderr.
- ithkuil 12y agoThe advantage of outputting help text to stdout is that you can pipe it to a pager. And since getting help is not an error, the exit code is 0. From what you pasted it doesn't seem to check whether stdout exists, but whether stdin is a terminal. The intended use case is "your_program <input_file" => read from stdin; "your_program" => complain that you forgot a cmdline parameter (instead of blocking waiting for you to type something).
- deleted 12y ago[deleted]
- bobbyi_settv 12y agoHe's following the philosophy that says when you run "program --help", the expected output of the program is the usage info and therefore it should go to stdout, but when you run "program <invalid args>" and it prints the same usage info, that is an error message and should go to stderr.