How To Add Bash-Completion For Kubectl Command

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

Adding Kubectl To Bashrc

  1. $ vim $HOME/.bashrc

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

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

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

  1. $ vim $HOME/.bashrc

    Then scroll down below and add the following:

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

  3. $ source $HOME/.bashrc

I hope you enjoy the article.


Posted by Shehu Awwal

DevOps Engineer, Interests around Kubernetes, Infrastructure, Security & Automation.

Leave a Reply

Your email address will not be published. Required fields are marked *