Skip to content

Instantly share code, notes, and snippets.

@michaelkirk
Created May 4, 2012 16:51
Show Gist options
  • Save michaelkirk/2596181 to your computer and use it in GitHub Desktop.
Save michaelkirk/2596181 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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
Copy link

nitriques 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
Copy link

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
Copy link

jschaf 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