Jeff Ochoa

Delete merged branches from your local git history

Delete merged branches from your local git history - JeffOchoa.me

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:

https://stackoverflow.com/questions/6127328/how-can-i-delete-all-git-branches-which-have-been-merged#card

Share This Article

Continue reading