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.
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