Stop Writing Shell Scripts to Sort Git Branches — Git Already Does It
A simple git config command replaces years of shell scripting for sorting branches by last commit date.
If you juggle many git branches, you've probably written a script to list them by most recent commit. The author of this TIL did, and ran it daily for years. The script loops over git branch, extracts each branch name, runs git log to get the commit date, and then sorts the output. It works, but it's slow and fragile.
Modern git has a built-in solution: git branch --sort committerdate. You can also set it globally with git config branch.sort committerdate, so every git branch call sorts by last commit date by default.
This isn't just a convenience — it's a reminder that git's plumbing is richer than most of us use. The --sort option accepts any key from git-for-each-ref, which exposes fields like authordate, creatordate, contents:size, and even upstream and push refs. That opens up sorting branches by message size, by upstream relationship, or by creation date — without any scripting.
The tradeoff: committerdate sorts by the last commit on the branch, not the last time the branch was touched (e.g., by a merge or rebase). If you want the latter, you'd need creatordate or a custom script. But for most workflows, committerdate is exactly what you want.
This is a small tip, but it's the kind of thing that saves time every single day. And it's a good excuse to read the git-for-each-ref manpage — there's more there than you'd think.
Turns out with modern git it's totally unnecessary. Just configure git branch to sort by the last commit date.
Source: Ryan Greenberg
Discussion
0 Comments
Be the first to start the discussion.