Recent Git Branches

December 04, 2020

EDIT: A friend of mine sug­gest­ed an improve­ment to the below:

    recent = !git checkout $(git branch --sort=-committerdate | fzf)

which also has the added ben­e­fit of high­light­ing the cur­rent branch with a *:

* branch-1

A trick I use a lot — a way to view and switch between recent­ly-used branch­es:

Let’s see how it works.

Using Git’s for-each-ref, we can get a list of all Git refs:

git for-each-ref

This returns every­thing, includ­ing remote refs and tags. I only want to see those refs that cor­re­spond to local branch­es, so filter them:

git for-each-ref refs/heads/

and sort them by latest commit time­stamp:

git for-each-ref refs/heads/ --sort=-committerdate

and short­en the output so it’s just dis­play­ing the ref name:

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

To make it nicer, com­bine it with fzf, the com­bi­na­tion of which is shown below as a snip­pet from my .gitconfig:

    list-recent = "!sh -c 'git for-each-ref  refs/heads/ --sort=-committerdate \

    recent = "!sh -c 'git checkout $(git list-recent | fzf -m)'"