Shehu Awwal

How To Add Bash Completion For Kubectl Command

Kubernetes · Kubernetes

1 minute

December 2, 2021

The kubectl comes in a single binary package that you can run in your current directory or move it over to /bin/ or any other directory, But we still want that auto-completion instead of having to type the whole command.

Adding Kubectl To Bashrc

vim $HOME/.bashrc

This will open the bashrc file on the current user, and add the following down below:

source <(kubectl completion bash)

This will read the kubectl command with completion, Then we will need to source the .bashrc file to take effect as well.

source $HOME/.bashrc

Now the completion should be able to work when we type kubectl with tab key twice.

You Can also make use of this, ensure you are root user, after adding it, you can login and it will take effect for all users.

kubectl completion bash > /etc/bash_completion.d/kubectl

Alias The Kubectl Command

How about instead of typing kubectl, we just want to type k or kl or whatever and also with auto-completion. Then let’s add the following to the .bashrc file.

vim $HOME/.bashrc

Then scroll down below and add the following:

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

As you can see where kcl is, you can replace it with your own alias that you want. Type the following in the terminal.

source $HOME/.bashrc

Comments: