Tidy git branches

Branching in git is an ease to work with and literally takes seconds. You can be working on your own feature, switch to a colleague’s feature then switch to production code to check a bug all within a few keystrokes and in no time at all.

Branching is easy and a convenience. However this often leads to many branches and over time that leads branch hell. We want to be able to clean up all those merged in branches that we were too lazy to delete 3 months ago. Here’s the code to do the purge.

git branch --merged develop | grep -v 'master$' | grep -v 'develop$' | xargs git branch -d

# find all local branches merged in to develop
# dont delete master or develop branches
# then do it

If you’re working with github or you’re storing your code in a ‘central’ repository you’ll likely be experiencing the same thing on the remote server as well. Here’s the modified version to purge remote branches.

git branch -r --merged develop | sed 's/ *phil\///' | grep -v 'master$' | grep -v 'develop$' | grep -v '^  dave' | grep -v '^  kevinbrowne' | xargs -I% git push phil :%

# mostly likely change the first part to master. use this branch to test if things have been merged in
# sed part. use this to remove the name of your remote in my case phil. most likely to be origin
# grep any branches you want to keep
# last part. change name to your remote
# you can do a dry run by removing the last section

With these little scripts you can keep periodically prune your branches every so often and not need to this every time and also prevent your repository from over growing.