How to delete all local git branches except master#

During the normal course of a project, git repositories can accumulate a number of branches locally. A few branches may be fine, but sometimes they can pile up and lead to an unacceptably large number of branches. That's when it is time for a branch clean up!

If you want to delete all the local branches except the master branch, here's what you can do.

First, make sure you are on master:

$ git checkout master

Then run this command:

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

It will delete all the local branches, whether they have been merged to master or not.

Now, what if you want to be a little less adventurous and delete only branches that have been merged to master?

This command will do that for you:

$ git branch | grep -v '^*' | xargs git branch -d

Git has a command for deleting branches (git branch -D <branch1[, branch2, ...]> or git branch -d <branch1[, branch2, ...]>), but it does not provide an option for specifying "except this branch or these branches". So how does the command above work?

We use three commands to accomplish what we want to achieve.

  1. git branch - lists the local branches
  2. grep -v '^*' - filters out the branch starting with * (current branch, which was master)
  3. xargs git branch -D - passes the filtered branch names to the git command git branch -D

The process of passing on the output of one command to to another is made possible by the use of | (pipeline).

In the very unlikely case, where you would like to preserve some other branch and not master, you just need to checkout the branch of your interest, instead of master.

Assuming the branch is named diamond, this is what you should do:

$ git checkout diamond
$ git branch | grep -v '^*' | xargs git branch -D

Summary#

git doesn't provide the ability to delete all the local branches except one or more, but we can pipe together git branch, grep, and xargs git branch to delete all the local branches except the branches of our choice.

References#

  1. Git - git-branch
  2. WikiPedia - grep
  3. WikiPedia - xargs
  4. WikiPedia - Pipeline (Unix)