Show Git Branches by Date

Posted by Grego on February 3, 2023

Did you know you can sort git branches by commit dates?

Git 2.7 and Newer

Starting from git 2.7 (Q4 2015) you can use the --sort option:

git branch --sort=committerdate

If you want the most recent branch on top, add a - in front of the sort type:

git branch --sort=-committerdate

If you always want this behavior you can set it as a default:

git config --global branch.sort --committerdate
git branch # will now show sorted by committer date always

from man git-branch:

--sort=<key>
   Sort based on the key given. Prefix - to sort in descending order of the value. You may use the --sort=<key> option multiple times, in which case the last key becomes the primary key. The keys supported are the same as those in git for-each-ref. Sort order defaults to the value configured for the branch.sort variable if exists, or to sorting based
   on the full refname (including refs/... prefix). This lists detached HEAD (if present) first, then local branches and finally remote-tracking branches. See git-config(1).

For more sorting options, See the FIELD NAMES section in man git-for-each-ref

Older Versions of Git

Older versions of git can use for-each-ref:

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

Here you would pass refs/heads, refs/remotes, refs/tags or just refs/ for all kinds. You can also combine them by adding spaces in between.