This is git bash completion's built-in function for this purpose.
After declaring your alias, bind the correct auto-complete function to it:
# Main git completions (prior to git 2.30, you an use _git instead of __git_main)
alias g="git"
__git_complete g __git_main
alias go="git checkout"
__git_complete go _git_checkout
alias gp="git push"
__git_complete gp _git_push
On Ubuntu 18.04 (Bionic) the following works. Add something like this snippet (with your aliases) to your preferred bash configuration file e.g. .bashrc, .bash_aliases.bash_profile.
# define aliases
alias gc='git checkout'
alias gp='git pull'
# setup autocompletion
if [ -f "/usr/share/bash-completion/completions/git" ]; then
source /usr/share/bash-completion/completions/git
__git_complete gc _git_checkout
__git_complete gp _git_pull
else
echo "Error loading git completions"
fi
In general the format of the __git_complete directive is the following:
To add to other excellent answers: normally you have a lot of Git aliases and it may be tedious to manually forward completions for all of them. Here's a small trick to do this automatically:
if [ -f "/usr/share/bash-completion/completions/git" ]; then
# Enable Git completions for aliases
. /usr/share/bash-completion/completions/git
for a in $(alias | sed -n 's/^alias \(g[^=]*\)=.git .*/\1/p'); do
c=$(alias $a | sed 's/^[^=]*=.git \([a-z0-9\-]\+\).*/\1/' | tr '-' '_')
if set | grep -q "^_git_$c *()"; then
eval "__git_complete $a _git_$c"
fi
done
fi
I realize you're specifically asking about bash aliases, but for those coming here looking for autocomplete in bash for complex git aliases, see here.
In particular:
# If you use complex aliases of form '!f() { ... }; f', you can use the null
# command ':' as the first command in the function body to declare the desired
# completion style. For example '!f() { : git commit ; ... }; f' will
# tell the completion to use commit completion. This also works with aliases
# of form "!sh -c '...'". For example, "!sh -c ': git commit ; ... '".