Sort branches by last commit date

Ryan Greenberg

2 min read Original article ↗

I have too many git branches and like many people I developed a convoluted script to show me the most recent ones. I ran this command many times a day for years:

function branches {
  for k in `git branch | sed "s/^..//"`; do
    echo -e `git log --color -1 --pretty=format:"%Cgreen%ci %Cblue%cr%Creset" "$k"`\\t"$k";
  done | sort
}

This outputs the date as the first column in the output so that sort works. Turns out with modern git it’s totally unnecessary. Just configure git branch to sort by the last commit date:

git config branch.sort committerdate

You can also supply this on a one-off basis as git branch --sort committerdate.

What else can you sort by? The manual says “The keys supported are the same as those in git-for-each-ref(1).” The manpage for git-for-each-ref lists a ton of fields, including some that don’t make sense to me as sort keys. Here are a few that stood out as interesting:

  • authordate, committerdate, creatordate, taggerdate
  • contents:size: The size in bytes of the commit or tag message.
  • push: The name of a local ref which represents the @{push} location for the displayed ref.
  • refname: The name of the ref (the part after $GIT_DIR/) (this is the default).
  • upstream: The name of a local ref which can be considered “upstream” from the displayed ref.

Git