Cleanup of git branches

In our work projects we use a lot of git branches. Over time, the number of branches in my local repository grows and it gets more complicated to find specific branches. For this reason I like to cleanup untracked branches every now and then, and because this is only an issue every few months, I keep forgetting how to exactly do this. This little post is meant as I reminder for myself, but maybe it’s also useful for others.

One source of leftover branches result from merging pull requests on a remote git hosting platform like Github. Remote branches might get deleted there, but you’ll still have your local tracking branches. You can get rid of these by using the command:

git remote prune origin

You can add the --dry-run option, if you want to list unused local tracking branches only.

In order to discover local branches, that have already been merged, switch to your project’s main branch and enter the following command on a terminal:

git branch --merged

This will show you all branches that have been merged into your main branch. Note that the output also contains the name of your main branch (master, if your project still uses old terminology). You could now manually delete all branches, that have already been merged, but that’s tedious. In order to automatically delete them, we can combine a few commands:

git branch --merged >/tmp/merged-branches && \
vim /tmp/merged-branches && \

xargs git branch -d </tmp/merged-branches && \
rm /tmp/merged-branches

Let’s go through these commands: First we’ll write the merged branches into a temporary file. We then open that file with vim, which gives us the opportunity to remove any branch that we do not want to delete (like the main branch). Once finished we use xargs to individually delete every remaining branch in our temporary file (through stdin) using git branch -d. Afterwards we cleanup by deleting the temporary file.

This is fine and it works, but who remembers all this two hours later? I’ve created a little script that can be put on your path:

#!/usr/bin/env bash
git remote prune origin && \
git branch --merged >/tmp/merged-branches && \
vim /tmp/merged-branches && \
xargs git branch -d </tmp/merged-branches && \
rm /tmp/merged-branches

Now you can just enter git-remove-merged-branches.sh in a project.

References