Fixing Bash autocompletion on MacOS for kubectl and KOPS
--
One helpful feature of the Linux Shell is the autocompletion functionality, so in this post we show you how to extend autocomplete to kubectl commands.
Most shells allow command completion, typically bound to the TAB key, which allows you to complete the names of commands stored upon your PATH, file names, or directory names.
Problem:
By default MacOS comes with an inferior version of Bash which doesn’t support most of useful autocompletion features for DevOps utilities like Kubectl, Kops or other handy cli tools.
Default version installed:
$ echo $BASH_VERSION
3.2.57(1)-release
Solution:
Bash autocompletion is supported from version 4.1.x and luckily installing a new version is pretty straightforward using Brew:
$ brew install bash
We need to make some adjustments to add it to the default shell list in MacOS.
1. Update /etc/shells with new added Bash version
Open file below with nano or vi (or any other editor)
$ vi /etc/shells
Add the next line at the end of the file:
/usr/local/bin/bash
So it will look like this:
# List of acceptable shells for chpass(1).
# Ftpd will not allow users to connect who are not using
# one of these shells./bin/bash
/bin/csh
/bin/ksh
/bin/sh
/bin/tcsh
/bin/zsh
/usr/local/bin/bash
2. Change default Shell being used.
Now we will need to update the default shell by running the following command (this will request you MacOS password!):
$ chsh -s /usr/local/bin/bash
3. Confirm new Bash version is the default
We can easily validate if you have a latest version of Bash enabled as your default shell. Close your terminal and rerun the echo $BASH_VERSION command:
$ echo $BASH_VERSION4.4.12(1)-release
4. Adding Bash autocompletion addons by brew
Install the required generic brew packages, this will make sure that specific autocompletion modules can be added.
$ brew install bash-completion
$ brew tap homebrew/completions
5. Now adding autocompletion for kubectl, kops or any other cli tool.
To load kubectl, kops or any other autocompletion bash modules into our Bash source, we use the following command:
$ source <(kubectl completion bash)$ source <(kops completion bash)
However, this will only load it for our current session, so to make sure it remains during reboots we can add it in our bash_profile.
Open ~/.bash_profile with your favorite editor and add the following lines to the end of the file: (If ~/.bashrc already exists, strongly recommended to use ~/.bashrc)
source <(kubectl completion bash)
source <(kops completion bash)if [ -f $(brew --prefix)/etc/bash_completion ]; then
. $(brew --prefix)/etc/bash_completion
fi
Now you can use kubectl by using autocompletion on your Mac, by typing kubectl followed with a tab after each command you want to be completed.
Kubectl now supports auto-completion just like the Linux shell ;-)