Bash Autocomplete – How to Output String Completions to stdout

autocompletebashcompgen

Some of the git commands have many options, and it would often be useful to search through them for the one I need – I was just looking for the option which controls the TAB width in git-gui, but there are about 200 completions for git config. An obvious workaround is to copy all the completions into an editor and search through them, but I'd rather do

[something] | grep tab

There are no man or info pages for compgen, help compgen doesn't even explain its own options, and there's no auto-complete for compgen (how's that for irony?).

PS: compgen -A doesn't work.

PPS: This is not a question about git-gui – The solution to the tab width question was elsewhere.

PPPS: This is not about auto-completing commands, only command parameters.

Best Answer

You can use the following function, which use the same way sudo auto-completion generate the completion list:

comp() {
    local COMP_LINE="$*"
    local COMP_WORDS=("$@")
    local COMP_CWORD=${#COMP_WORDS[@]}
    ((COMP_CWORD--))
    local COMP_POINT=${#COMP_LINE}
    local COMP_WORDBREAKS='"'"'><=;|&(:"
    # Don't really thing any real autocompletion script will rely on
    # the following 2 vars, but on principle they could ~~~  LOL.
    local COMP_TYPE=9
    local COMP_KEY=9
    _command_offset 0
    echo ${COMPREPLY[@]}
}
comp git config ''

where _command_offset is defined in bash-completion (package).

NOTE: the function need to be run in a interactive shell (i.e. if it is in a file, the file need to be sourced instead of just run.) or the necessary completion rules/functions will not be defined.

PS. compgen -A only works for builtin actions, what you should have tried (but doesn't work either) is compgen -F (or actually compgen -o bashdefault -o default -o nospace -F _git). The reason this doesn't work (and doc for bash built-in commands including compgen/complete) can be found in bash(1).

Related Question