Pruning Local GIT branches

Introduction

GIT is an amazing source control system, although if there is not an automatic pruning policy setup, you can find yourself with hundreds of local branches.  I did some googling and didn’t find much on the topic, other than deleting branches one at a time!  I solved it myself and am sharing my solution here.

I could write some code that interfaces directly with GIT (I have done this before with Mecurial), although I wanted something quick and easy.

Solution

There are already a few tools that can help, it’s just a case of putting them together.

git branch

This will give you a list of all your local branches.

We want to filter these branches to the ones we’re interested in (i.e. all until a certain branch name).  There’s a great tool for searching:

grep BranchNameHere -B 1000

So we can use grep to find 1000 branches before the “BranchNameHere” is found.

Now we need to actually delete the branch:

git branch -d BranchName

(Uppercase D if you want to include branches not merged or pushed)

Then to get all this to work together we can pipe into each command:

grep branch | grep BranchNameHere -B 1000 | xargs git branch -d

To be safe, you can omit the last pipe and the preceding text to view what branches are going to be removed.

Leave a comment