Bash – Displaying usage comments in functions intended to be used interactively

bashfunctioninteractive

I have a number of functions defined in my .bashrc, intented to be used interactively in a terminal. I generally preceded them with a comment describing its intended usage:

# Usage: foo [bar]
# Foo's a bar into a baz
foo() {
  ...
}

This is fine if browsing the source code, but it's nice to run type in the terminal to get a quick reminder of what the function does. However this (understandably) doesn't include comments:

$ type foo
foo is a function
foo ()
{
    ...
}

Which got me thinking "wouldn't it be nice if these sort of comments persisted so that type could display them?" And in the spirit of Python's docstrings I came up with this:

foo() {
  : Usage: foo [bar]
  : "Foo's a bar into a baz"
  ...
}

$ type foo
foo is a function
foo ()
{
    : Usage: foo [bar];
    : "Foo's a bar into a baz";
    ...
}

Now the usage is included right in the type output! Of course as you can see quoting becomes an issue which could be error-prone, but it's a nicer user experience when it works.

So my question is, is this a terrible idea? Are there better alternatives (like a man/info for functions) for providing users of Bash functions with additional context?

Ideally I'd still like the usage instructions to be located nearby the function definition so that people viewing the source code also get the benefit, but if there's a "proper" way to do this I'm open to alternatives.

Edit these are all fairly simple helper-style functions and I'm just looking to get a little extra context interactively. Certainly for more complex scripts that parse flags I'd add a --help option, but for these it would be somewhat burdensome to add help flags to everything. Perhaps that's just a cost I should accept, but this : hack seems to work reasonably well without making the source much harder to read our edit.

Best Answer

I don't think that there is just one good way to do this.

Many functions, scripts, and other executables provide a help message if the user provides -h or --help as an option:

$ foo() {
[[ "$1" =~ (-h|--help) ]] && { cat <<EOF
Usage: foo [bar]
Foo's a bar into a baz
EOF
return;
}
: ...other stuff...
}

For example:

$ foo -h
Usage: foo [bar]
Foo's a bar into a baz

$ foo --help
Usage: foo [bar]
Foo's a bar into a baz