Search code examples
bashautocompletetab-completioncompgen

How do I autocomplete nested, multi-level subcommands?


I am trying to develop an autocomplete or tab-complete feature for my own set of commands.

For example, assume foo is my binary:

CLI>> foo [TAB] [TAB]

It should show the main commands configure and show.

Then if I select configure, it should show the subcommands CM, DSP and NPU:

CLI>> foo configure [TAB] [TAB]
DSP NPU CM`

I only know how to tab-complete and display for the first level - how can I get the second level as well?

I will place this in /etc/completion.d.

My Code:

_foo()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    words=("${COMP_WORDS[@]}")
    cword=$COMP_CWORD
    opts="configure show"
}

I'm stuck as how to add sub commands CM DSP NPU under configure.


Solution

  • Here's an example script for your two-level case (with a section for subcommands of show to show how it's done - you can just delete those three lines if they're not relevant to your case):

    _foo()
    {
        local cur prev
    
        cur=${COMP_WORDS[COMP_CWORD]}
        prev=${COMP_WORDS[COMP_CWORD-1]}
    
        case ${COMP_CWORD} in
            1)
                COMPREPLY=($(compgen -W "configure show" -- ${cur}))
                ;;
            2)
                case ${prev} in
                    configure)
                        COMPREPLY=($(compgen -W "CM DSP NPU" -- ${cur}))
                        ;;
                    show)
                        COMPREPLY=($(compgen -W "some other args" -- ${cur}))
                        ;;
                esac
                ;;
            *)
                COMPREPLY=()
                ;;
        esac
    }
    
    complete -F _foo foo
    

    Hopefully it's fairly obvious from that example how you'd extend it to three-level commands etc., as well.