How to Remove All the Git Branches Except the Master Locally
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
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 😉
An aspiring Fullstack Developer, currently mastering front-end. I love writing and teaching others the little I know. Join me on my journey.
Initially, I was thinking you'd delete the branch
Pikachu from the repo, but it seems the command deletes all repos except