Git Clean

The majority of my programming projects are tracked using git. It’s decentralized, stable, compact and easy to configure, so it’s an obvious choice as a developer.

It allows me to split off my work into separate, tracked branches so I can work on multiple features or changes at the same time without risking the health of the codebase.

Once I’ve finished a feature in a branch, I can merge it into master and can happily use the new code. But the branch I worked in is still there. After several dozen mini “projects” like this, my git branch list starts getting very long.

Luckily, I found this short command line script to clean up branches that have been merged into master!

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

This lists all branches that have been merged into master (including master), filters out the master branch, and then runs git branch -d for each branch name found this way.

But wait! If you work with a remote git repository, this still leaves all of those branches out there! Never fear, there’s a (pretty complicated) way to clean those up, too!

git branch -r --merged  master | grep origin | grep -v '>' | grep -v master | xargs -L1 | cut -d"/" -f2- | xargs git push origin --delete  

This lists all remote branches merged to master, finds all of the branches from origin (you can replace origin with your remote destination of choice), filters out branches you don’t want to delete, and then runs git push origin --delete for each branch found this way.

Tada! Sparkling clean git branches locally and remote.

Published by EyeOfMidas

Game Programmer, Web Developer, Linux Server Admin

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: