Jeff Ochoa

Delete merged branches from your local git history

Jeff Ochoa

How often do you delete old branches from your local Git repositories?

I never did that before, until now, let me show you how.

The following command lists all the branches in your repository, and then delete them one by one.

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

In this case, we deleted all the branches except master and dev, if you want to exclude another branch just add the name to the grep sequence like so:

egrep -v "(^\*|master|dev|another-branch)" 

Daily usage

I use oh-my-zs, so what I did was to add a new alias to my ~/.zshrc file

alias gclean="git checkout master && git branch --merged | egrep -v \"(^\*|master|dev)\" | xargs git branch -d"

Now every time I want to clean my repository, need to run gclean, that's it.


Thanks to Paul Conroy for sharing the original article:

Jeff Ochoa

Subscribe to receive updates in your mail inbox