Skip to main content
Preslav Rachev
  1. My Writings /Programming /

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

·2 mins
List and switch back and forth between multiple git branches with ease.

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!

How To Checkout The Previous Branch In Git
Presentation of a simple Git shortcut to move back to the branch you were previously on.

Have something to say? Join the discussion below 👇

Want to explore instead? Fly with the time capsule 🛸

You may also find these interesting

I Am Moving My Obsidian Vault Away From iCloud

·1 min

I spent quite some time last Saturday morning, moving my main Obsidian vault away from iCloud. I want to make myself use Obsidian more, but syncing via iCloud has been such a pain - regularly ended up having duplicated or even lost notes in-between syncs.