Question

Kubernetes kubectl bash completion with alias

I am using kubectl with bash completion , but I prefer to use a shorter alias for kubectl such as ks , what changes I need to make to get the bash completion work with alias ks

 46  39047  46
1 Jan 1970

Solution

 37

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 ks' >>~/.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
2018-10-20