jmcantrell/bashful

usage command example / questions

eleftrik opened this issue · 2 comments

@jmcantrell First of all, thank you for sharing your work!

Could you please give a pretty detailed example of usage command?

I guess I have to manually check if each parameter/option has been passed or not, then call usage accordly, isn't it?

Thank you

It's really not complicated. All it does is arrange a handful of variables and format them a little.
It only accepts one argument and it's an error code which gets passed to exit. In fact, usage is essentially an alias to exit plus some documentation.

It's intended to be used like this:

unset OPTIND
while getopts ":h" option; do
    case $option in
        h) usage 0 ;;
        *) usage 1 ;;
    esac
done && shift $(($OPTIND - 1))

Or:

some_command_that_may_return_nonzero || usage 1

Here are some examples to show it's full range:

The only way to get any output is to set the script name.

source bashful-messages
SCRIPT_NAME=thingy
usage

Which outputs:

Usage: thingy [OPTIONS] 

GENERAL OPTIONS

    -h    Display this help message.

Adding some more variables:

source bashful-messages
SCRIPT_NAME=thingy
SCRIPT_ARGUMENTS="[key] [value]"
SCRIPT_USAGE="This is a thing that sets a value for the given key."
SCRIPT_DESCRIPTION="Sometimes you want to define a value for some key.
In those instances, you may consider using this command.
At some point, I plan on making this description more detailed."
SCRIPT_EXAMPLES="thingy some_setting on
thingy number_of_things 5
thingy -l
thingy -d some_setting"
SCRIPT_OPTIONS="-d    Delete key.
-l    List keys."
# for these, if they're set to anything, it will show in usage
INTERACTIVE=0  # interactive is off, but still set
VERBOSE=1      # verbose is on
usage

Will output this:

Usage: thingy [OPTIONS] [key] [value]
This is a thing that sets a value for the given key.

Sometimes you want to define a value for some key.
In those instances, you may consider using this command.
At some point, I plan on making this description more detailed.

EXAMPLES

thingy some_setting on
thingy number_of_things 5
thingy -l
thingy -d some_setting

GENERAL OPTIONS

    -h    Display this help message.

    -i    Interactive. Prompt for certain actions.
    -f    Don't prompt.

    -v    Be verbose.
    -q    Be quiet.

APPLICATION OPTIONS

    -d    Delete key.
    -l    List keys.

Try removing or changing those values to see the effect. Revisiting this function is reminding me how semi-pointless it is. It's very opinionated, and minimally useful, but it illustrates a way to formalize a style for command line documentation.

Thank you very much @jmcantrell!