How to change git branch output order

As of git 2.7.0 this will work:

git branch --sort=-committerdate

Edit: Since Git version 2.19 (late 2018), Git obeys a branch.sort configuration. Since Git version 2.7.0 (early 2016), git branch itself allows sorting, so that you do not have to use git for-each-ref directly.

Edit

Alas there are apparent problems with the sorting options taken by git-for-each-ref. Since that command is (obviously) explicitely aimed at showing refs and accepts the --sort option, I'm thinking of this as a likely bug[1].

Here is the best options I can further come up with, but the output is quite far estranged from the original format (because they rely on decorating revisions after the fact to refer to branches). Ah well, maybe it is of use for you:


[1] if this were git-rev-list or git-log I would think the problem would be that we're not actually walking a revision tree; we're actively trying to show only tips of trees, without walking them.

Temporary alternative

git log --no-walk --date-order --oneline --decorate \
       $(git rev-list --branches --no-walk)

This would give you a list similar to

4934e92 (HEAD, origin/testing, origin/HEAD, testing) reviewed INSTALL file as per #1331
6215be7 (origin/maint, maint) reviewed INSTALL file as per #1331
1e5e121 (origin/emmanuel, emmanuel) buffers: adjust the size in zfsfuse_stat
e96783e (origin/compress, compress) buffers: adjust the size in zfsfuse_stat
f6e2c6c (origin/unstable, unstable) revert the fatal condition again
dd52720 (origin/master-lucid, master-lucid) lucid
3b32fa7 (tag: 0.7.0, origin/master, master) panic revocation of 0.7.0-0 package necessitates an update
6eaa64f (origin/maint-0.6.9, maint-0.6.9) Replace remount by drop_caches (on rollback)

_As you can see, the result can be a bit overwhelming in the presence of many remote (tracking) branches, which effectively alias the same revisions. However, the result is properly ordered by (descending) date.

The correct (unfortunately broken?) approach...

No, but you should be able to do

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

(use --sort='-*authordate' for author date ordering)

On my test repo, this yields:

compress
emmanuel
maint
maint-0.6.9
master
master-lucid
testing
unstable

Alias

you can create a git alias to do this: append the following lines to .git/config

[alias]
branch2 = git for-each-ref --sort='-*committerdate' --format="%(refname:short)" refs/heads/

From then on, you could just say git branch2


Stujo's answer is my favorite, but I wanted to go one step further and make sort by committer date my default git branch behavior. Here's how:

git config --global branch.sort -committerdate

Remove the - before committerdate to sort the other way.

Now git branch will always be sorted by date!

Tags:

Git

Git Branch