In order to get easy bash completion for my scripts’ command line switches, I have been exploring the _parse_help function in /etc/bash_completion (debian sid, bash v4.2-1, bash-completion v1:1.99-3).
My script generates a help message in what I believe to be standard GNU format:
MYSCRIPT [OPTIONS]
Usage:
-h, --help Show this help message
-o, --option Some option
I then activate completion via complete -F _parse_help ./myscript.
Unfortunately this does not give the desired result. Upon first tab ./myscript <TAB> (note, just a single keypress) an unformatted list appears containing –help and –option, not the shortened versions. Worse, completion of either option fails. In fact, just typing a dash causes _parse_help to completely stop generating output.
The whole thing feels very much broken, and I cannot find much reference of it online. Is this function perhaps considered obsolete? Is there another standard method of command line completion based on parsing –help output?
According to the bash reference manual the
-F functionexpects to read the word list from a variableCOMPREPLYIt would appear that
_parse_helpdoes not set this required variable and would therefor not be suited as a function forcomplete -F. The output is obviously echo’d as is evident from executing the function.@gertjan What you were attempting can be accomplished using the
-W wordlistoption instead.Completion works as expected and
--hwill complete--helpor where there were multiple arguments like with “–” it will only list the appropriate options.If we were trying to use a function however it is not sufficient alone to only set
COMPREPLYas you will see from the next example.NOTE:
COMPREPLYis a bash array and requires the brackets()when setAs you can see, even though the options are displayed,
completenow expects us to do the filtering. We can accomplish this withcompgenbut first we need to determine what the current argument is to filter against. The function_get_comp_words_by_refcan help with this by populating the$curvariable, as per our final example.The complete implementation using a function with
_parse_helpfor bash completion.nJoy!