How to Remove All the Git Branches Except the Master Locally

Stay in the loop!

Subscribe to my newsletter and stay up-to-date with my latest blog posts. Get an email every time I post something new.

I'm writing this post a note to my future forgetful self.

Today, I ran into a really stupid issue. I worked on updating a remote git repo, and I've already merged and deleted a branch on GitHub with this name, let's call it Pikachu for the sake of having an example.

So, after merging Pikachu to master, I realized that I needed to make another change to the file I've just pushed. "No biggie" I thought...

git checkout -b Pikachu

And then ....

fatal: A branch named 'Pikachu' already exists.

At first I was like ....

Until I realized that the branch I had locally was the one preventing me from generating one. I already merged and removed the same branch on GitHub. In my mind, every git pull on master should have removed the local branch, but for obvious reasons that would be a totally stupid thing to happen.

So, how do I clean up my local working repository so that I remove a gazillion stale branches I have locally? You need to get this into your terminal:

git branch | grep -v "master" | xargs git branch -D

In case you have a branch that contains the word "master" this won't work. Instead, you need to:

git branch | grep -ve " master$" | xargs git branch -D

That's it. Hope this note to my forgetful future self helps some of you as well 😉

Comments (2)

Gyen Abubakar's photo

Initially, I was thinking you'd delete the branch Pikachu from the repo, but it seems the command deletes all repos except master, right?

Milica Maksimović's photo

Editor in Chief @appsignal, former Community Manager @Hashnode

Yes, it removes all the local branches except the master.