All Articles

How to remove local merged branches?

Photo by The Creative Exchange on Unsplash unsplash-logoThe Creative Exchange

One of the best feelings in software development is to finish a feature. Then you merge it, so can delete the branch you’ve been working for weeks! The feeling is even more powerful when you are able drop two or three branches before starting the next one. Tools like Github and Gitlab even have a button to ‘Delete all merged branches’, so I can’t not be the only one who loves it :)

The problem is, they still there, on your machine. Git is a distributed VCS. So things, especially potentially harmful like a deletion, are not automatically replicated between different nodes. It is easy to see it when typing:

git branch

So how can you remove them? The first thing is to remove the references to the remote server, usually called origin. The second one is to use the output from the —merged parameter to list our targets. You could use the option -d to remove each one of them manually. Or you can wrap it all around using this cool trick:

git remote prune origin
git branch --merged >/tmp/merged-branches && vi /tmp/merged-branches && xargs git branch -d </tmp/merged-branches

This applies a thin “security” layer showing you the branches it is going to remove, so you can edit the list sparing some of them. You do not want to remove develop or master, do you?

And that does the trick. Your workspace is now clean and ready for more coding!