Have you ever felt like you had too many local branches after a couple of days / weeks of programming?

On a bad day, an actual complete screenshot would take 3 screens…

When you work on your git-versioned project, you usually follow (or should follow) something like git flow. It’s a great way to keep your team up-to-date with releases, while having proper independent branches for development. One of the (small) caveats of this workflow is that it multiplies the number of branches. And if you lose track of some, or don’t think about deleting the old local ones, you end up with the screenshot above.

You would like to delete all your branches, but would be too afraid of losing that one branch where you found a hack to speed up your build by 30% but some random plugin started going crazy…and you kept it as a branch aside for later. For this git has a simple option:

git branch --merged=master

This gives us all the branches that have been merged into master . Now you can replace master with any other branch, or commit hash, or leave blank for HEAD . Remember that you should also be up-to-date with your local branches.

So you would want to use this with a git branch -d :

git branch -d $(git branch --merged=master)

Nice ! Except that master happens to be merged into master , and because we don’t want to delete it , this becomes that:

git branch -d $(git branch --merged=master | grep -v master)

And DONE, you just removed all the useless branches on your local repository!