Skip to content

Recent Git Branches

Posted on:December 4, 2020

EDIT: A friend of mine suggested an improvement to the below:

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

which also has the added benefit of highlighting the current branch with a *:

  master
* branch-1
  branch-2

A trick I use a lot — a way to view and switch between recently-used branches:

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 everything, including remote refs and tags. I only want to see those refs that correspond to local branches, so filter them:

git for-each-ref refs/heads/

and sort them by latest commit timestamp:

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

and shorten the output so it’s just displaying the ref name:

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

To make it nicer, combine it with fzf, the combination of which is shown below as a snippet from my .gitconfig:

[alias]
    list-recent = "!sh -c 'git for-each-ref  refs/heads/ --sort=-committerdate \
    --format=\"%(refname:short)\"'"

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