Skip to main content

Overriding Git's Tab-Completion in Bash

Only suggest local branches for tab-completion

If you use git from the command line like I do, then you probably already know that you can define aliases in ~/.gitconfig like this:

[alias]
	co = checkout

Or you can create the alias using the command line and make git itself write in ~/.gitconfig:

$ git config --global alias.co "checkout"

With this alias you can type “git co” instead of “git checkout”, and tab-completion works with the alias as well.

But did you know that during tab-completion bash will actually look for a function named after the alias before using the normal completion rules? In the above example it will look for a function named “_git_co”, which means we can override it.

With the above alias you can put this in your ~/.bashrc

# Override "co" alias to only complete local branches
_git_co() {
  __git_complete_refs --mode="heads"
}

Now when you type “git co” and then tab it will only suggest local branches, while “git checkout” will suggest all branches as usual.

I have found this incredibly usefull when I been put on a project where branches haven’t been removed after merging, so there are potential hundreds of branches and I just want to change between two or three local branches.

Shameless plug

And while we’re talking about git and bash I will just shamelessly advertise my own bash-git-prompt-hook that will change your bash prompt to a nice looking prompt that displays all the git info and other cool stuff.

Bonus alias

And finally, as a bonus here is a little bash alias that you can put in ~/.bash_aliases that will change directory to the root of the current git repo no matter how deep you are:

alias cdroot='cd "$(git rev-parse --show-cdup)"'