Kubernetes kubectl bash completion with alias

I have this in my .bashrc to get alias and auto completion.

source <(kubectl completion bash | sed s/kubectl/k/g)


from the official docs

# after installing bash completion

alias k=kubectl
complete -F __start_kubectl k

https://kubernetes.io/docs/reference/kubectl/cheatsheet/#bash


A more recent update from the docs:

  • Source the completion script in your ~/.bashrc file:
    echo 'source <(kubectl completion bash)' >>~/.bashrc
    
  • Add the completion script to the /etc/bash_completion.d directory:
    kubectl completion bash >/etc/bash_completion.d/kubectl
    

If you have an alias for kubectl, you can extend shell completion to work with that alias:

echo 'alias ks=kubectl' >>~/.bashrc
echo 'complete -F __start_kubectl k' >>~/.bashrc

You can basically do this:

$ echo "source <(kubectl completion bash | sed 's|__start_kubectl kubectl|__start_kubectl ks|g') >> ~/.bashrc

Out of date:

A slight change from what is described here.

In essence, you are substituting the following in the kubectl completion bash output:

if [[ $(type -t compopt) = "builtin" ]]; then
    complete -o default -F __start_kubectl kubectl
else
    complete -o default -o nospace -F __start_kubectl kubectl
fi

With this:

if [[ $(type -t compopt) = "builtin" ]]; then
    complete -o default -F __start_kubectl ks
else
    complete -o default -o nospace -F __start_kubectl ks
fi

Tags:

Kubernetes