Clean up local Git branches

As we developers work, we often will be assigned some work. Often this can be a Github Issue, a Jira Ticket, or some other system, that basically can assign something to you to be dealt with.

Once that happens, if you're using Git, you will probably create a new branch in order to keep your changes separate from a "working" instance of your project.

If you do this a lot, you can end up with a large list of branches, that could easily become unclear as to which branch you were working on. Or if you get distracted for a long time, you might forget the branch name.

The best thing to do is probably to keep your branching clean when you merge something into master. Which you can easily do in the Terminal by running a command. In this case git branch -d nameOfBranch.

Often though, we forget to do this, and you end up with a list of branches that becomes unmanageable.

I recently found myself in this situation recently, and finally got myself to a point where I knew most of the branches I had in my list had been merged, or that were old enough that I wasn't going to return to them.

So I did a google search and found a pretty handy little one-liner command that would help with this. And here it is:

git branch --merged | egrep -v "(^\*|master)" | xargs git branch -d

What this is doing is creating a list of branches that have been merged, this is done with the git branch --merged command. The result of this command, which is a list of branch names, gets piped to egrep, and then filters outmaster since you probably don't want to get rid of that. This is done with egrep -v "(^\*|master)".

Note, if you want to exlude other branches, like a dev or staging branch, you should add them here like (^\*|master|dev|staging).

Once our excluded branches are filtered out be egrep, the resulting list is then piped to xargs. Xargs lets you build and execute commands from a standard input, and in this case we will passing our result list to git branch -d which is the command to delete a branch from our local git repository.

So if you run the command as typed, it is going to list the Merged branches on the git repository, exclude the master branch, and then delete those. Or in a shorter summary: Delete merged branches exluding master.