How to delete local merged branches in git in seconds
Jotted down on 01 January 2022
171 words
The fact that we can delete local merged branches in git within seconds is a discovery to me.
Let's take a look at the code:
1git branch --merged | egrep -v "(^\*|main|master|development|production|release-*|gh-pages)" | xargs git branch -d
- git branch --merged: lists all the merged branches
- egrep -v "(^\*|main|master|development|production|release-*|gh-pages)": excludes the matching branches (including the current one)
- xargs git branch -d: deletes the branches
Just make to sure to put all the branch names in the second step which are not supposed to be deleted. Any branch which does not match the criteria will get deleted.
Any fresh branch created on top of the above branches will also get deleted. You can use reflog to restore the branch in that case.
And finally, you can create an alias for this command in your .zshrc
so you don't have to type it every time:
delete unwanted merged branches (dumb)
1alias dumb="git branch --merged | egrep -v "(^\*|main|master|development|production|release-*|gh-pages)" | xargs git branch -d"