psuzzi
psuzzi

Reputation: 2277

How to complete a bash function with multiple parameters/options?

I defined a function alias for a command: aa and I defined a _complete_aa function which is used as a suggestion for the aa command via complete -F _complete_aa aa (See code below)

aa(){
    anothercommand ${@}
}

_complete_aa(){
    COMPREPLY=($(compgen -W "clean build start" "${COMP_WORDS[1]}"))
}

complete -F _complete_aa aa

When I use the function I have an unexpected behavior:

When I type aa cle and press TAB the prompt correctly completes my input into aa clean

But, when I type aa clean bui and press TAB, the prompt completes my inuput into aa clean clean, while I expect it should change into aa clean build.

I guess my error is in the below completion function, Which does not take care of the index of the current word under completion.

_complete_aa(){
    COMPREPLY=($(compgen -W "clean build start" "${COMP_WORDS[1]}"))
}

Question: how I should change the body of the _complete_aa function so that I get completion of the current word into clean build start for each new option/parameter I am typing ?

Upvotes: 0

Views: 277

Answers (2)

Benjamin W.
Benjamin W.

Reputation: 52152

The completion function gets positional parameters, of which $2 is the "word being completed", so you could do this:

_complete_aa(){
    COMPREPLY=($(compgen -W "clean build start" "$2"))
}

If your completion really is just the selection of given words, you can use the simpler -W completion instead:

complete -W 'clean build start' aa

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 141085

Index COMP_WORDS with current word index.

aa() {
    anothercommand "$@"
}

_complete_aa() {
    COMPREPLY=($(compgen -W "clean build start" "${COMP_WORDS[$COMP_CWORD]}"))
}

complete -F _complete_aa aa

The "${COMP_WORDS[1]}" is always going to be the first word after the command.

Upvotes: 1

Related Questions