Cleaning Up Local Git Branches

About 1 min reading time

Over time, I accumulate several local Git branches in various projects. To maintain clarity, I regularly delete all branches except the main branch.

To avoid having to constantly search for the command, I'd like to share it with you here:

git branch | grep -v "main" | xargs git branch -d

git branch lists all local branches. grep -v "main" filters out the main branch from this list, as I don't want to delete it. xargs git branch -d executes the git branch -d command on the remaining branches.

If you want to keep multiple branches, you can extend the command:

git branch | grep -v "main" | grep -v "develop" | xargs git branch -d

Here, two branches, main and develop, are filtered out from the list and thus not deleted.

I hope this tip helps you keep your system as tidy as it helps me.


This post is based on my opinion and experience. It is based on what worked for me in my context. I recognize, that your context is different.
The "Just Sharing" Principle