To set up kubectl autocompletion for Bash on a Linux system, follow these steps:
Prerequisites
- Ensure that you have kubectl installed. If not, you can download and install it from the official Kubernetes install page.
- Ensure that you have bash-completion installed. Most modern Linux distributions have bash-completion available in their package repositories.
Steps
1. Install bash-completion
If bash-completion is not already installed, install it using your package manager.
For Debian/Ubuntu:
sudo apt-get update
sudo apt-get install bash-completion
For CentOS/RHEL:
sudo yum install bash-completion
For Fedora:
sudo dnf install bash-completion
2. Enable bash-completion
Ensure that bash-completion is sourced in your .bashrc file.
Open your .bashrc file in a text editor:
nano ~/.bashrc
Add the following line at the end of the file (if it’s not already present):
[[ $PS1 && -f /usr/share/bash-completion/bash_completion ]] && . /usr/share/bash-completion/bash_completion
Save the file and reload your .bashrc:
source ~/.bashrc
3. Set up kubectl autocompletion
Add the kubectl completion script to your .bashrc file.
Open your .bashrc file in a text editor (such as nano or vi):
nano ~/.bashrc
Add the following line at the end of the file:
source <(kubectl completion bash)
Optionally, you can also set up alias autocompletion if you use an alias for kubectl (e.g., k
):
alias k=kubectl complete -F __start_kubectl k
Save the file and reload your .bashrc:
source ~/.bashrc
Verification
To verify that the autocompletion is working, you can start typing a kubectl command and press Tab to see if it suggests completions. For example, type kubectl get po and press Tab to autocomplete the word pods.
That’s it! You have successfully set up kubectl autocompletion for Bash on a Linux system.