6

I'm trying to make a generic autocomplete function (which actually takes several parameters, and has a bunch of shared logic), so that I can easily and neatly maintain a long list of similar commands, with similar autocompletes (number of arguments, etc).

I've got a bash function, which takes an argument (simplified as much as possible):

_autocomplete() {
    COMPREPLY=( $(compgen -W "$1" -- "${COMP_WORDS[COMP_CWORD]}") )
    return 0
}

And when I reference it, using a command which takes a function name as an argument, I want to also pass it a parameter to run in the function:

complete -F "_autocomplete example_param" some_function

However, this does not work when I hit tab, and instead errors with:

some_function bash: completion: function `_autocomplete example_param' not found

Is this a limitation of complete?
Is there any way around this, or a better approach?

Thanks.

0

1 Answer 1

3

The -F option is supposed to be followed by just a function name. If you want to execute a command with options, you need to use -C. But the command is required to print the completions to standard output, not set COMPREPLY. So change the function to:

_autocomplete() {
    COMPREPLY=( $(compgen -W "$1" -- "${COMP_WORDS[COMP_CWORD]}") )
    for reply in "${COMPREPLY[@]}"
    do
        printf '%s\n' "$reply"
    done
    return 0
}

complete -C "_autocomplete example_param" some_function
Sign up to request clarification or add additional context in comments.

2 Comments

in this case the function some_function shows arguments but doesn't auto-complete them; do you know how to fix that?
I don't personally use customized completions, but I can't imagine why it would list completions that it doesn't use. The two features should go hand in hand.

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.