How to Remove All the Git Branches Except the Master Locally

Subscribe to my newsletter and never miss my upcoming articles

Note: I've moved all my projects to use the main instead of master branch.

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

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