Cleanup Your Local Git Repo

Often we see that we are working on a big project and it takes a while for us to switch between local branches or load a branch locally into our IDE (integrated development environment). In most cases, it is either the local cache files like Node libraries or several Maven repo versions, or unwanted files and libraries. You will have to look into your project to see what could be the reason. But what is often ignored is how we do not clean up local branches after working on them which might lead to a lot of stales local branches which are doing nothing but making it difficult to load the project initially when you restart the IDE and switch between branches. A good practice is to delete local branches when you are done working on a feature and it is merged to the upstream repository, but we often miss out. Here we will be going through some basic commands to clean up such local branches without affecting the remote ones.

The first step is to figure out which branches are lying on your local system. So head over to your command line, go to the repository directory, and run this.

git branch

This will list down all your local branches. Let us assume the worst case, that you have too many local stale branches. Want to know the count? This is how you can check that too.

git branch | wc -l

To delete a single branch you can use this command.

git branch -D <branch name>

But the above one will take forever to perform one by one. Let us make use of some regex and grep here. Now let's say you want to simply delete all the local branches except the master (or as they call it now as main). Then you can simply run this command:

git branch | grep -v "master" | xargs git branch -D

The above command would delete any and every branch in local in the current repository except the ones that start with the phrase master. But in reality we might require to delete certain branches and keep certain ones.

For example, let's say you want to delete all the branches starting with the phrase "hotfix", for example, "hotfix/prod-email-issue", "hotfix_PROJ-1234", etc. In such cases, the following command will be helpful.

git branch | grep "hotfix" | xargs git branch -D

If you are a RegEx pro, then you could even write complicated patterns to delete only specific branches and leave out the rest. This command below will help you:

git branch | grep -E '<regex pattern>' | xargs git branch -D

Example:

git branch | grep -E 'PROJ-\d\d\d\d$' | xargs git branch -D

And that's how you can reduce the load from your local git repo while reducing the number of stale local branches. Hope it was helpful, do share your comments or suggestions, or appreciation below.