Sunday, 24 February 2013

Delete unused branches from your remote Git repo

Without regular housekeeping, your Git repos can become cluttered with feature branches that were either already merged into master, or just abandoned as simple experiments. Especially on larger projects, things can quickly start to get messy!

How might we go about cleaning these unwanted branches up?

One way would be to delete each branch at a time, using git push combined with our branch name, prefixed with a colon:

git push origin :<unwanted branch>

This works fine for one or two branches, but what if we want to remove many branches in one go?

git br -r | egrep -v "master|<other branches to keep>" | sed "s/\// :/" | xargs -n 2 git push

This script takes all the remote branches, filters them for branches we want to keep, constructs the 'origin :<remote branch>' command suffixes, and then passes each one to git push.

If you're at all nervous, back up your repo locally first!