Shell Completion for kubectl
Typing full kubectl commands gets tedious quickly. Shell completion lets you press Tab to auto-complete resource types, resource names, flags, and even namespaces.
Bash Completion
First, install the bash-completion package if you do not already have it:
# macOS
brew install bash-completion@2
# Debian/Ubuntu
sudo apt-get install bash-completion
Next, generate the completion script and source it:
# Generate the completion script
kubectl completion bash
# Add it to your .bashrc so it loads on every new shell
echo 'source <(kubectl completion bash)' >> ~/.bashrc
# Reload your shell
source ~/.bashrc
If you use an alias like k for kubectl, you need to extend completion to the alias:
echo 'alias k=kubectl' >> ~/.bashrc
echo 'complete -o default -F __start_kubectl k' >> ~/.bashrc
source ~/.bashrc
Zsh Completion
Zsh completion works similarly. Add the following to your ~/.zshrc:
# Add kubectl completion to Zsh
echo 'source <(kubectl completion zsh)' >> ~/.zshrc
# Reload your shell
source ~/.zshrc
If you get an error about compdef, make sure compinit is loaded by adding this line before the completion source:
autoload -Uz compinit && compinit
Testing Completion
After setup, try typing a partial command and pressing Tab:
kubectl get po<Tab> # completes to "pods"
kubectl get pods my-<Tab> # completes to matching pod names
kubectl -n <Tab> # lists available namespaces
Key Takeaways
- Shell completion saves time and reduces typos
- Bash users need the
bash-completionpackage installed first - Add the
sourcecommand to.bashrcor.zshrcso it persists - Completion works with aliases if you set up the
completebinding - Both resource types and resource names are auto-completed