Question

How to Enable kubectl Autocompletion in Bash?

Posted April 20, 2021 1.9k views
Linux BasicsLinux CommandsKubernetes

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!

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.

×
Submit an Answer
1 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