Git Tip: List the Most Recent Branches You Have Been Working On

In most projects I have worked on, we ended up using feature branches. Since branches in git are cheap, every ticket, no matter how large or small the changes, would have its own feature branch. You would end up having many of those, often, having to switch between one or another.

Git has a built-in checkout attribute for switching back to the previous branch you were working on. This is usually as simple as:

git checkout -

which is a shorthand for:

git checkout @{-1}
# Changing the index will switch back to the n-th previous branch

Switching back and forth is easy, but what if you wanted to go to the branch you were working on a couple of days ago? I bet you don't even remember its name, to begin with. In case you use a git client, such as SourceTree, or something built into your IDE of choice, you might already be having such a functionality. Yet, if you are a fan of the command line, you might be stuck. Git does not provide it out of the box, but can easily be extended with an alias that allows just that.

Let's create a git command that displays a list of the past 10 branches one has worked on, sorted in reverse order:

git for-each-ref --sort=-committerdate --count=10 --format='%(refname:short)' refs/heads/

Running the command above will give us exactly what we need, but is tedious to write and remember. Thanks to git's aliasing support, we can map this long string of options to a git shorthand sub-command, say, rb.

Find an open ~/.gitconfig and add the following line of code as part of the [alias] section. If there is no [alias] section, add it as well.

[alias]
	rb = for-each-ref --sort=-committerdate --count=10 --format='%(refname:short)' refs/heads/

Once you have saved the file, the new git rb command should be at your disposal.


Acknowledgements and Further Reading

Thanks to Jason Rogers for being the one whom I got to learn this tip from!