Bash – Configure autocomplete for the first argument, leave the others alone

autocompletebash

I have a utility that takes a load of different arguments. For now, I want to autocomplete the first argument, but leave all the others to fall through to normal autocompletion. How do I do that?

function _my_autocomplete_()
{
    case $COMP_CWORD in
        1) COMPREPLY=($(compgen -W "$(get_args_somehow)" -- ${COMP_WORDS[COMP_CWORD]}));;
        *) # What goes here?
    esac
}

complete -F _my_autocomplete_ mycommand

Best Answer

Apparently I completely missed your question. The answer is that there's no well-defined "normal autocompletion." However, if you know what sort of thing you'd like it to complete (files, aliases, pids, variable names, etc.), you can give one or more flags to compgen. See this compgen manual page, specifically the -A options under complete (they're the same). E.g. if you want to complete file names, you would use this:

compgen -f -- "${COMP_WORDS[COMP_CWORD]}"

If you want to complete commands (incl. aliases, functions, etc.), you can use this:

compgen -back -A function -- "${COMP_WORDS[COMP_CWORD]}"

Use $COMP_CWORD to get the index of the word being completed. If the index isn't 1, set $COMPREPLY to () and return.

COMP_CWORD

    An index into ${COMP_WORDS} of the word containing the current 
    cursor position. This variable is available only in shell functions
    invoked by the programmable completion facilities
Related Question