I wrote the autocomplete function for my command, but it is not autocomplete the argument after the option flag

function _qpdm_complete() 
    local cur prev options my_list

    my_list="quantum alpha betta omega operation"   

    if [[ ${cur} == -* || ${COMP_CWORD} -eq 1 ]] ; then
        COMPREPLY=( $(compgen -W "${options}" ${cur}) )
        return 0
        COMPREPLY=( $( compgen -W "${my_list}" -- ${cur}) )

complete -F _qpdm_complete qpdm

then in terminal

qpdm <TAB>

qpdm -opt 

qpdm -opt<TAB>

qpdm -opt  
quantum alpha betta omega operation

qpdm -opt o<TAB>


qpdm -opt o
omega operation

but get

qpdm -opt o  
quantum alpha betta omega operation 

What is missed in my _qpdm_complete()?

1 Answer 1


Probably just a typo: COMP_WORD is not a variable used by Bash (or, at least, I am unable to find it in the manual). You should have written COMP_WORDS instead.

In your code, both cur and prev are always empty because ${COMP_WORD[COMP_CWORD]} and ${COMP_WORD[COMP_CWORD-1]} refer to an undefined variable. And compgen, correctly, always returns all the option values that match an empty cur.

  • It works! Thanks. Just another tiny question: How can I prevent that after "qpdm -opt omega <TAB>" it is not respond with "qpdm -opt omega -opt" but stop the completion process? Oct 6, 2020 at 12:31
  • It really depends on your use case. For instance, you may add if [[ $COMP_CWORD -gt 2 ]]; then return 0; ... as the first test (before or at the beginning of the if block you already have).
    – fra-san
    Oct 6, 2020 at 12:38
  • It works, thanks a lot! Oct 6, 2020 at 13:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .