1

Consider an environment variable that can take a list of arbitrary possible meaningful values. For an example of such an environment variable consider AWS_PROFILE. The list of possible values can be easily computed by some command, e. g. aws configure list-profiles. Is there any way I can write a custom completion such as whenever I type

$ AWS_PROFILE=<TAB>
$ AWS_PROFILE=partial-profile-nam<TAB>

or

$ export AWS_PROFILE=<TAB>
$ export AWS_PROFILE=partial-profile-nam<TAB>

I can get the completion function run and suggest the list of possible values.

0

1 Answer 1

1

Here's a rough example:

# cat compspec
_aws_profiles()
{
    echo {foo,bar}-profile-{1,2}
}

_export_comp()
{
    local cur=$2
    local profiles=$( _aws_profiles )

    if [[ $COMP_LINE == *' AWS_PROFILE='* ]]; then
        COMPREPLY=( $( compgen -W "$profiles" -- "$cur" ) )
        return
    fi
}

complete -F _export_comp -o default -o bashdefault export
$ source ./compspec
$ export AWS_PROFILE=<TAB><TAB>
bar-profile-1  bar-profile-2  foo-profile-1  foo-profile-2
$ export AWS_PROFILE=f
$ export AWS_PROFILE=f<TAB>
$ export AWS_PROFILE=foo-profile-
$ export AWS_PROFILE=foo-profile-<TAB><TAB>
foo-profile-1  foo-profile-2

The above would not work for $ AWS_PROFILE=<TAB>. As a workaround you can define an alias which expands to nothing:

alias %=''
complete -F _export_comp -o default -o bashdefault %

Then you can

$ % AWS_PROFILE=<TAB><TAB>
bar-profile-1  bar-profile-2  foo-profile-1  foo-profile-2
Sign up to request clarification or add additional context in comments.

7 Comments

Is it just not possible to have plain AWS_PROFILE=<TAB> complete?
no, as far as i know.
This, unfortunately, has a side effect of shadowing other completions for export, such as completing environment variable names. For example $ export PA<TAB> would complete to $ export PATH= without this loaded. Any chance we can have both this and whatever default completions there were before together?
what's your output of complete -p export without loading my script?
you can try adding else COMPREPLY=( $( compgen -v -- "$cur" ) ) to the if block
|

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.