Follow on twitter
Apr 26th, 2019

Delete merged branches from your local git history

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.

Credits

Thanks to Paul Conroy for sharing the original article:

How can I delete all Git branches which have been merged?

I have many Git branches. How do I delete branches which have already been merged? Is there an easy way to delete them all instead of deleting them one by one?

Jeff
4 months ago
Share: