One Liner: Cleaning Up Old Git Branches

I am very lazy about deleting local git branches. I just checked and I have 100+ branches! WTF. That makes it a real pain to find the one I was working on yesterday. So first, let me get rid of the ones that I’ve already merged into master.

git branch --merged | egrep -v '(master|develop)' | xargs git branch 

But I still have 58 branches left! Lets try sorting by committer date:

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

This command gives me a list of branches sorted by commit date. The output looks something like:

BL-1302567-dnp-global-dns "10 months ago"
BL-1311324-scheduled-scale-down "8 months ago"
hackweek-dnp-deploy "4 months ago"
BL-1305305-dnp-secretsmanager "3 months ago"
BL-1311060-dnp-deploy-v2.6.1 "3 months ago"
dnp-breakfix "3 months ago"
BL-1307167-sas-api-elb "2 months ago"
BL-1307165-patch "9 weeks ago"
BL-1307166-sas-dns "8 weeks ago"
BL-1307441-product-project "8 weeks ago"
sas-deploy-fix "8 weeks ago"
... 

Now I can use this to find branches where the top commit is older than a few months

git for-each-ref --sort=committerdate refs/heads/ --format='%(refname:short) "%(committerdate:relative)"' | egrep -v "(master|develop)" | egrep "([4-9]|[1][0-2]) months ago" | xargs -n2 bash -c 'git branch -D $0'

Here I used egrep to remove the master and develop branches as a precaution, then again to select only branches that are 4 “months ago” or older. Then just pass the output to xargs and you’re all set.