Kubectl autocompletion in MacOS

March 20, 2019

MacOS comes with a really old bash version. Check the version from the environment variable..

$ echo $BASH_VERSION
3.2.57(1)-release

We can install a newer version of bash via Homebrew package manager, get Homebrew from here https://brew.sh.

Install the new version of Bash

Once you have installed the command Homebrew you can install Bash and the bash-completion for this new version.

$ brew install bash
$ brew install [email protected]

The new version of Bash is installed in /usr/local/bin/bash.

Include the new Bash in the allowed shells

Edit the file /etc/shells and add at the end the new Bash path.

$ sudo vi /etc/shells
# 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

Change the default shell

Set to the default shell to the current user.

$ chsh -s /usr/local/bin/bash

Install kubectl autocomplete

You can check what kubectl recommend for install the autocomplete.

$ kubectl completion -h

Store the configuration for the automcompletion.

$ kubectl completion bash > ~/.kube/kubectl_autocompletion

Edit ~/.bash_profile to include the source and load the bash_completion, include these lines at the end of the file.

if [ -f /usr/local/share/bash-completion/bash_completion ]; then
  . /usr/local/share/bash-completion/bash_completion
fi

source ~/.kube/kubectl_autocompletion

Now you can restart your shell and use kubectl autocomplete.

Links