September 23, 2015

Git: Delete all merged branches

If you work on some project long enough, then you can end up with a lot of old, already merged branches. The solution is simple. Delete them:

git branch --merged | grep -v "\*" | grep -v "master" | xargs git branch -d

Explanation

Show all merged branches:

git branch --merged

Remove current branch and master branch from the output:

grep -v "\*" | grep -v "master"

Call git branch -d for each branch:

xargs git branch -d

Keeping the habit

Of course no one is going to type such a long command regularly. So it is a perfect candidate for new shell alias:

alias delete_merged_branches='git branch --merged | grep -v "\*" | grep -v "master" | xargs git branch -d'

delete_merged_branches is much easier to type, especially with the tab autocomplete. I delete old branches pretty often thanks to this alias.

Hey there!

My name is Patrik Bóna and I am the only programmer at Memberful. This blog is kind of dead, but I just started my own Ruby on Rails screencast. Follow me on Twitter if you want to be notified about my newest videos.