Skip to content

Delete local git branches with ease, a quick guide

Posted in Productivity

Everybody loves branches. Branching is the greatest feature that source control management tools like git offers. However, it can get out of hand quickly when unattended. Sometimes you work on a project for a few weeks or months and start stacking branches on branches on branches. You get branches for bug fixes, for new features, for debugging, and so on. What happens when you want to delete local git branches? Do you just delete them one by one using git-branch like a peasant? Que nenni! We can do better, especially if more than a couple of branches are involved. This is why I’m writing this today for your eyes only.

After a swift DuckDuckGo search, I found that someone already asked about a way to delete local git branches. Not much scrolling was needed to find a solution from the user pankijs that suggested to execute three commands that fit a single line:

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

Three things happen here. First, “git branch” lists all the branches available locally. Then, “grep -v “master”” filters that output to exclude the master branch if present. Finally “xargs git branch -D” deletes branches returned after the filtering one by one. It’s pretty good but we can go further.

As it turns out, the first comment from Schwern on that reply suggests grepping based on the “*” character rather than the branch name. Why? I hear you ask, well when running “git branch“, a star prefixes the current branch. Therefore, the current branch gets excluded which gives us this line:

git branch | grep -v ^* | xargs git branch -D

Now, we can do one better, we can ensure that we choose the branch we want to preserve. Say we want to locally preserve the “new-branch” branch we can do it by adding a checkout to that branch.

git checkout new-branch && git branch | grep -v ^* | xargs git branch -D

Now you have all the tools you need to delete local git branches with ease. Thanks for passing by and I hope this was useful to you. If you want more Git goodness, check out the git section of my cheatsheet of epicness right here.

Photo by Min An from Pexels

Be First to Comment

    Leave a Reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    %d bloggers like this: