Cleaning Up Merged Git Branches


After having created and merged many branches, looking through local branches can become cumbersome. A long list of branches is especially problematic when I'm returning to an older branch and I can't seem to remember a correct keyword to use with grep to find what I'm looking for. Here's a quick rundown of how to list and delete merged branches from your local clone.

The --merged flag is used to list all the branches which have been merged:

  git branch --merged

Now in order to remove all our merged branches, without having to name them one by one, we can pipe the output of listing merged branches to the flag used to delete branches:

  git branch --merged | xargs git branch -D

Details on xargs, which is a fantastic utility, can be found here.

Now before we're done, I'd like to back up and add a little protection against deleting branches unintentionally. The command above will delete branches that have been merged into whatever the current branch is. For example, if I'm working in a feature-branch workflow where my branches are being merged into master, and master may be merged into a feature branch, I want to make sure I don't accidentally delete master if running this from a feature branch.

We can use grep's -v flag to exclude something. Here's the updated command with a pipe to grep to exclude master.

  git branch --merged | grep -v master | xargs git branch -D

And that's it! For convenience I also alias this command. I could go a couple steps further and add this as a hook if I wanted to be super vigilant about keeping my branches clean.

Here's a few related references that may be useful:

comments powered by Disqus