I want to get a list of all the branches in a Git repository with the "freshest" branches at the top, where the "freshest" branch is the one that's been committed to most recently (and is, therefore, more likely to be one I want to pay attention to).
Is there a way I can use Git to either (a) sort the list of branches by latest commit, or (b) get a list of branches together with each one's last-commit date, in some kind of machine-readable format?
Worst case, I could always run git branch
to get a list of all the branches, parse its output, and then git log -n 1 branchname --format=format:%ci
for each one, to get each branch's commit date. But this will run on a Windows box, where spinning up a new process is relatively expensive, so launching the Git executable once per branch could get slow if there are a lot of branches. Is there a way to do all this with a single command?
As of git 2.19 you can simply:
You can also:
So whenever you list branches in the current repository, it will be listed sorted by committerdate.
If whenever you list branches, you want them sorted by comitterdate:
Disclaimer: I'm the author of this feature in git, I implemented it when I saw this question.
Use the
--sort=-committerdate
option ofgit for-each-ref
;Also available since Git 2.7.0 for
git branch
:Basic Usage:
Result:
Advanced Usage:
Result:
I like using a relative date and shortening the branch name like this:
Which gives you output:
I recommend making a bash file for adding all your favorite aliases and then sharing the script out to your team. Here's an example to add just this one:
Then you can just do this to get a nicely formatted and sorted local branch list:
Update: Do this if you want coloring:
Git v2.19 introduces
branch.sort
config option (see branch.sort).So
git branch
will sort by committer date (desc) by default withscript:
Update:
So,
and
List of git branch names, ordered by most recent commit…
Expanding on Jakub’s answer and Joe’s tip, the following will strip out the "refs/heads/" so the output only displays the branch names:
Command:
Result:
The other answers don't seem to allow passing
-vv
to get verbose output.So here's a one-liner that sorts
git branch -vv
by commit date, preserving color etc:If you additionally want to print the commit date, you can use this version instead:
Sample output:
It's probably more readable split into multiple lines:
This should also work with other arguments to
git branch
, e.g.-vvr
to list remote-tracking branches, or-vva
to list both remote-tracking and local branches.