19

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.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Puneeth
  • 419
  • 1
  • 6
  • 18

1 Answers1

36

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.

Demitri
  • 13,134
  • 4
  • 40
  • 41
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • 3
    That's exactly what I was in need of. Let me come back to you as I advance. – Puneeth Jul 29 '13 at 09:51
  • 2
    Interesting, how much cool stuff one can find around here ;-) – GhostCat Apr 06 '17 at 13:30
  • I've executed in my terminal. Is not woking. I am typing "configure show " but nothing happens. – sensorario May 21 '19 at 07:34
  • @sensorario the script defines a command `foo` with two mutually exclusive arguments `configure` and `show` (which themseleves have sub-arguments). Try typing `foo` and then hitting Tab a couple of times … – Zero Piraeus May 21 '19 at 11:24
  • The problem was that I was putting code inside a file and the executing it. Eveything works with `source file.sh` where file.sh contains the script. Thank you so much – sensorario May 21 '19 at 12:10
  • Hey @ZeroPiraeus, would you mind giving some pseudocode of how a three-level setup would work? your example seems to be the cleanest I have seen googling around but can't figure out how to do a third level. Thanks! – Carles Figuerola Apr 07 '22 at 14:50