0

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 ?

0

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Clear explaination, and both the proposed solutions works. Thanks!
1

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.

1 Comment

Also this solution works. This solution goes more in the details, and it is more useful in case one wants to write a complex function that deals with the current position of the word.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.