Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
sort remote branches by age
#!/bin/sh
#
# Too many crusty old git branches? Run this to find likely candidates for deletion
# It lists all the remote branches and sorts them by age.
#
# Folks at pivotal shared this with me
#
#$ . show-remote-branch-info.sh
# 2012-05-04 09:42:29 -0700 4 minutes ago Ted & Bill \torigin/hey_Bill
# 2012-05-03 16:27:23 -0700 17 hours ago Anthony \torigin/develop
# 2012-03-26 20:35:35 +0000 6 weeks ago Susan \torigin/feature/jenkins
for k in `git branch -r|awk '{print $1}'`;do echo `git show --pretty=format:"%Cgreen%ci %Cblue%cr %Cred%cn %Creset" $k|head -n 1`\\t$k;done|sort -r
echo "If you're unable to remove a branch, it may already be gone from the remote. Try git remote prune origin (git remote prune --dry-run origin) to see what remote branch references will be deleted"
@ryanjones

This comment has been minimized.

Copy link

commented May 3, 2013

For local branches :D

for k in `git branch -a|awk '{print $1}'`;do echo `git show --pretty=format:"%Cgreen%ci %Cblue%cr %Cred%cn %Creset" $k|head -n 1`\\t$k;done|sort -r

Great gist! Thanks!

@juanstiza

This comment has been minimized.

Copy link

commented Jul 29, 2016

Thanks for the gist! my two cents: list only branches merged with master:
for k in git branch -a --merged master|awk '{print $1}';do echo git show --pretty=format:"%Cgreen%ci %Cblue%cr %Cred%cn %Creset" $k|head -n 1\\t$k;done|sort -r

@nitriques

This comment has been minimized.

Copy link

commented May 9, 2018

Here's a one-liner without the for k in (that does not work in bash for Windows). It uses awk instead.

git branch  | awk '$1=="*" { $1=$2; } { system("git --no-pager show --pretty=format:\"%Cgreen%ci %Cblue%cr %Cred%cn %Creset\" " $1 " | head -n 1 | sed -r \"s/(.*)/\\1\\t" $1 "/g\""); }' | sort -r
@JonAbrams

This comment has been minimized.

Copy link

commented May 29, 2018

I've played with this a bit and got it showing colours in OSX, sorted so that I don't have to scroll up to see the newest branch (which is usually the one I want to see), and without local files being printed out along with the branches:

for k in `git branch|awk '{print $1}'|grep -v "*"`; do \
  echo `git show --color=always --pretty=format:"%Cgreen%ci %Cblue%cr %Cred%cn %Creset" $k| \
  head -n 1`$k
done | sort
@jschaf

This comment has been minimized.

Copy link

commented Apr 22, 2019

I came up with a much faster variant that doesn't use subshells in a loop:

git for-each-ref --sort='-authordate' --format='%(authordate:short), %(authorname), %(refname:lstrip=2)' 'refs/remotes'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.