0

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
    COMPREPLY=()

    cur="${COMP_WORD[COMP_CWORD]}"
    prev="${COMP_WORD[COMP_CWORD-1]}"
    options="-opt" 
    my_list="quantum alpha betta omega operation"   

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

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>

expecting

qpdm -opt o
omega operation

but get

qpdm -opt o  
quantum alpha betta omega operation 

What is missed in my _qpdm_complete()?

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.

3
  • 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? – Roman Kaganovich Oct 6 '20 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 '20 at 12:38
  • It works, thanks a lot! – Roman Kaganovich Oct 6 '20 at 13:57

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.