How to install bash completion

How to install and enable bash auto-completion in Ubuntu and macOS?

Linux

How to install bash autocompletion in Linux

Installing bash-completion package on most Linux distributions like Ubuntu or Debian is as easy as executing:

sudo apt update
sudo apt install bash-completion

If you have it already installed, but it does not work, you might try to reinstall it:

sudo apt install --reinstall bash-completion

How to configure autocomplete in Linux bash

To make installed completions available in bash, you must source the definitions as part of your shell startup. Add the following to your ~/.bashrc file:

if ! shopt -oq posix; then
  if [ -f /usr/share/bash-completion/bash_completion ]; then
    . /usr/share/bash-completion/bash_completion
  elif [ -f /etc/bash_completion ]; then
    . /etc/bash_completion
  fi
fi

macOS

How to install bash autocomplete in macOS (OS X)

brew install bash-completion

How to configure autocompletion in macOS (OS X) bash

To make Homebrew’s completions available in bash, you must source the definitions as part of your shell startup. Add the following to your ~/.bash_profile file:

if type brew &>/dev/null; then
  for COMPLETION in $(brew --prefix)/etc/bash_completion.d/*
  do
    [[ -f $COMPLETION ]] && source "$COMPLETION"
  done
  if [[ -f $(brew --prefix)/etc/profile.d/bash_completion.sh ]];
  then
    source "$(brew --prefix)/etc/profile.d/bash_completion.sh"
  fi
fi