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
$ 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
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.
git branch- lists the local branches
grep -v '^*'- filters out the branch starting with
*(current branch, which was
xargs git branch -D- passes the filtered branch names to the
git branch -D
The process of passing on the output of one command to to another is made possible by the use of
master, you just need to checkout the branch of your interest, instead of
Assuming the branch is named
diamond, this is what you should do:
$ git checkout diamond $ git branch | grep -v '^*' | xargs git branch -D
git doesn't provide the ability to delete all the local branches except one or more, but we can pipe together
xargs git branch to delete all the local branches except the branches of our choice.