Remove All Git Branches Except Master

Remove All Git Branches Except Master

Ocassionally I end up with a lot of branches cluttering up my git repos. Often times this is a product of switching between a desktop and laptop during the same development cycle and forgetting to run git branch -D branch-name on branches that existed on both machines but are no longer needed, or from testing out ideas that never quite got to see the light of day. Needless to say during the course of a week or two a lot of extra branches can pile up. So once this mess piles up I can have easily 10 to 30 branches that are just cluttering up my repo. Granted you can go through one by one running the delete command, and if their are only a handful of branches this is fine, but anymore than a handful and it gets very tedious, and we didn't become programmers to do tedious tasks by hand.

So how do we get rid of them with out going through one by one and running the delete command individually? I wasn't able to find a easy command to handle this kind of task in git itself. But I did manage to use the power of the command line to pipe arguments from one command to the next, the result is a clean command that removes all branches except the ones your specifically want to keep.

So I wrote this command to clean up my git branch list.

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

If you need to exclude multiple branches you can do this.

$ git branch | grep -v -E (master|staging) | xargs git branch -D

For easier access if you need to do this frequently you can create an alias for this.

alias gclean="git branch | grep -v "master" | xargs git branch -D"