I'm trying to enable Bash completion for my own function called kctxt()
that delegates to kubectl
as follows:
kctxt() {
if [[ -z ${1+x} ]]; then
# show context if no arguments
kubectl config current-context
else
# set new context via completion
kubectl config use-context "$@"
fi
}
# For example, get completions just like:
# kubectl config use-context <tab><tab>
$ kctxt <tab><tab>
minikube eks-kube
$ kctxt ▊
First, I want to add that the standard completion for kubectl
is working just fine for me on macOS, and I have even installed complete-alias
to match alias k=kubectl
.
Is there a generic way to delegate the completion of a custom function to another command that also includes additional arguments? I've consulted many answers to similar questions that delegate a subcommand for another, like exec
and time
, but all I can get is completion on the main command.
I've also tried to define a custom completion function like this, and delegate to __start_kubectl()
(per complete -p kubectl
) without success.
_complete_kctxt() {
COMPREPLY=()
COMP_WORDS=(config use-context $2)
COMP_LINE="kubectl ${COMP_WORDS[@]}"
local prev=${COMP_WORDS[$COMP_CWORD]}
local cur=${COMP_WORDS[$((++COMP_CWORD))]}
COMP_POINT=${#COMP_LINE}
[[ -z "$cur" ]] && ((++COMP_POINT))
__start_kubectl kubectl $cur $prev
}
complete -F _complete_kctxt kctxt
I even tried to trace the completion of kubectl
via BASH_COMP_DEBUG_FILE
but that's pretty difficult to comprehend.