A simple way to clean up your git project branches

Florent Destremau
3 min readFeb 22, 2018

--

When you switch between branches and get lost in the names…

TD;LR: just use theses

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

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 thatmaster 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!

Much cleaner

All of them ? Nope, take a look at a git branch -a .

Once you know it, you can’t un-see the mess here

For this, git has a very useful option called --prune when you fetch remote branches that removes your local remote branches based on your repository.

git fetch --prune

And done !

Feels nice

Feels nice right ? Rince and repeat every time you get lost between local branches.

--

--