DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Preslav Rachev
Preslav Rachev

Posted on

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 -
Enter fullscreen mode Exit fullscreen mode

which is a shorthand for:

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

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/
Enter fullscreen mode Exit fullscreen mode

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/
Enter fullscreen mode Exit fullscreen mode

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!


This post was originally published on my blog

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.