DEV Community

Wojciech Korzeniowski
Wojciech Korzeniowski

Posted on

Git alias to delete merged branches

When you develop a project using multiple branches you may end up with a situation where you have branches which have already been merged into another branch and now serve no purpose.

I've created a git alias that deletes every branch that is already merged into master or another branch provided as an argument. To use it you need to modify .gitconfig and add following lines into it

  cleanup = "!f() { git branch --merged ${1:-master} | egrep -v \"(^\\*|${1:-master})\" | xargs --no-run-if-empty git branch -d; };f"

You can execute given command inside your terminal to achieve the same effect

git config --global alias.cleanup '!f() { git branch --merged ${1:-master} | egrep -v "(^\*|${1:-master})" | xargs --no-run-if-empty git branch -d; };f'

Then you can remove branches merged into master by invoking git cleanup. You can also provide a branch as an argument if your want to clean up a different branch eg. git cleanup development

Top comments (1)

ulska profile image
Ula Kowalska

Awesome, thanks for sharing! 💯