Today I Learned

TIL: Cleaning your Git repository by removing the unused branches

| 2 min read

Ever had a headache because of the number of branches you have on your repo locally? If so - I have something for you.

Working in a git project with some team members, and lots of tasks - you don't have any other way, than to work on a separate branch for each task. This is pretty useful, and GitHub also deals with it quite nice by deleting the merged branches... but that doesn't happen on your local repository. Also, git branches are light - they just point to a specific commit in the repo's history. And commits are also light. So having lots of branches won't cause huge performance issues, and thus - we don't remember to always delete the branch after we finish working on it - because it's not a big deal to keep it!

Unless it is. Sometimes you have to switch between branches, go to a branch that you just pushed, because you started working on an another task, and then you have to go back because you've got to make some changes from the code review. And that's the point where a problem araises - you don't remember the name of the branch... and you have to crawl through all the branches you have locally (assuming you're lazy enough to not just switch to the browser and check the branch on PR...). So this argumentation may not convince you. But still, even though you don't have problems with switching between branches, wouldn't it be nicer if you local repository was clean, and you had only, let's say, 5 branches? In my opinion - it would.

So if you're a person like me, you'll love this shell snippet!

git branch | grep -v "[branches]" | xargs git branch -D

Now just replace the [branches] with the names of your branches you want to have preserved divided by \| (for example master\|develop) and... voilà

Or you can go even further, and create a short bash script like this!

#!/bin/bash

BRANCHES=""

for branch in "$@"
do
    if [ "$BRANCHES" = "" ];
    then
        BRANCHES="$branch";
    else
        BRANCHES="$BRANCHES\\|$branch";
    fi
done

git branch | grep -v "$BRANCHES" | xargs git branch -D

I saved it in a file called gbc - Git Branch Cleanup - and I can use it like this (if I want to for example remove all the branches except master and develop): gbc master develop.

I do not take any responsibility for accidentally removed branches, broken repo histories and other f*ckups. If some wrong things happen - I recommend you to check out the tips on https://ohshitgit.com/