Cleanup Those Branches

After working on a project for any length of time, you are bound to have a lot of local branches lying around the place.  I had 302 of them as a matter of fact.  Git tells you to remove these local branches after they have been merged as they are no longer needed.  It does not however do this maintenance for you I’m afraid.  This is a manual process that must be done one by one using the following command:

$ git branch -d defect1234

This can be rather a pain in the rear end when you have 302 of them to do as I did.  Well fear not the bash shell gives you some power over the process.  The first thing we want to do is list all of our local branches that have been merged.

$ git branch --merged

Next we need to output this to a file so that we can use it to power our process later.

$ git branch --merged > ../branches.txt

Now we need to edit the file to keep around the fully merged branches that we want.  In my case I wanted to keep around my develop and master branches so I removed them from the file and saved my changes.

WARNING: Make sure that only the branches you want to delete are in this file.  If you accidentally delete a branch you will need to use the reflog to appropriate SHA value and rollback and recreate the branch from there.

Next I will use the power of the bash shell commands to read through the file and line by line delete the local branches.

$ while read line; do git branch -d "$line"; done < ../branches.txt

The command above will read each line from the file piped into the loop and issue the git delete branch command.  Git Mass Branch Delete Output

You can inspect the output on the screen and make sure that everything goes well and your done!

 

 

 

 

If only cleaning up your yard was this simple…

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s