How to Enable kubectl Autocompletion in Bash?

Hi all,

I am just getting started with Kubernetes and the kubectl command specifically.

As there are so many flags and arguments, is there a way to enable autocompletion just like in git?

So for example when I type kubectl get no[TAB] it would autocomplete nodes.

Thank you!


Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Accepted Answer

Hi there,

Yes, this is doable. What you would need to do is to first to make sure that you have the bash-completion package installed. If not, you could install it with the following command:

sudo apt-get install -y bash-completion

After that, you could generate the required kubectl completion rules with the kubectl completion bash command, and then store the rules in your .bashrc file. You could use the following command to do that:

echo "source <(kubectl completion bash)" >> ~/.bashrc

Note: Make sure to run this only once so that you don’t get duplicated rules.

After that, use the source command to activate the new rules:

source ~/.bashrc

Finally, if you were not now run kubectl get no[TAB] it will be autocompleted.

This is indeed quite handy! Hope that this helps. Regards, Bobby