DEV Community

Cover image for Bash Completion for kubectl
Boris Sh.
Boris Sh.

Posted on

Bash Completion for kubectl

Introduction

Bash is an sh-compatible command language interpreter that executes commands read from the standard input or from a file.
Bash can run most shell scripts without modification.

bash-completion is a collection of shell functions that take advantage of the programmable completion feature of bash on Ubuntu Linux.

How to add bash auto completion in Ubuntu Linux
The procedure is as follows to add bash completion in Ubuntu:

Open the terminal
Refresh package database on Ubuntu by running:

sudo apt update
Enter fullscreen mode Exit fullscreen mode

Get info about the bash-completion package:

apt info bash-completion
Enter fullscreen mode Exit fullscreen mode

Install bash-completion package on Ubuntu by running:

sudo apt install bash-completion
Enter fullscreen mode Exit fullscreen mode

Log out and log in to verify that bash auto completion in Ubuntu Linux working properly.

How to test programmable completion for Bash
Installer placed a shell script called /etc/profile.d/bash_completion.sh.
You can view it with help of cat command:

cat /etc/profile.d/bash_completion.sh
Enter fullscreen mode Exit fullscreen mode

You can add /etc/profile.d/bash_completion.sh to your ~/.bashrc file as follows:

## source it from ~/.bashrc or ~/.bash_profile ##
echo "source /etc/profile.d/bash_completion.sh" >> ~/.bashrc

## Another example Check and load it from ~/.bashrc or ~/.bash_profile ##
grep -wq '^source /etc/profile.d/bash_completion.sh' ~/.bashrc || echo 'source /etc/profile.d/bash_completion.sh'>>~/.bashrc
Enter fullscreen mode Exit fullscreen mode

I will recommend after reading this post read the bash man page using the man command or help command:

man bash
help complete
Enter fullscreen mode Exit fullscreen mode

Enable Kubectl Bash Completion

The bash completion script of kubectl can be generated with the following command:

kubectl completion bash
Enter fullscreen mode Exit fullscreen mode

The first way can be achieved through the adding ~/.bashrc:
Type the command in your command line tool, reload the bash shell and you are done.

echo ‘source <(kubectl completion bash)’ >>~/.bashrc
Enter fullscreen mode Exit fullscreen mode

First - User way

The second way is to adding access the system
In this mode, type command in your terminal

kubectl completion bash | sudo tee /etc/bash_completion.d /kubectl > /dev/null
Enter fullscreen mode Exit fullscreen mode

Second System way

Good Luck

Top comments (0)