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?

complete -F _my_autocomplete_ mycommand

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.


    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
  • I'm not familiar with bash completion. Does setting COMP_REPLY to () mean “default completions” rather than “no completions”? I don't see any mention of COMP_REPLY in the manual. – Gilles Mar 2 '12 at 22:51
  • @Gilles My bad, it's $COMPREPLY without the underscore. Setting COMPREPLY=() does tell bash not to offer any completion, I just checked to be sure. – Kevin Mar 2 '12 at 22:55
  • Ok. That's not what Dominic wanted: he wants the default completion to happen for the other arguments. – Gilles Mar 2 '12 at 23:04
  • Oh, I see. There is no 'default' completion, but you can get certain types (folders, functions, variables) with a command, I think it's certain flags on compgen. I'm traveling right now, I'll update when I get home. – Kevin Mar 2 '12 at 23:10
  • 2
    @DominicRodger in the complete -F _my_autocomplete_ mycommand command, add -o filenames. – Kevin Mar 21 '12 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.