How to delete a lot of remote branches on your Git Project?

March 13, 2021

Introduction

When you have a lot of remote branches on Git Project and you should do a little clean. To avoid ending up deleting branches that you don’t want you can use a bash script and filter what you don’t want to delete. First we will start to review what git is and why it is useful in a software development project.

What is Git?

Git is an Open Source Distributed Version Control System.

Control System: This basically means that Git is a content tracker. So Git can be used to store content, it is mostly used to store code due to the other features it provides.
Version Control System: The code which is stored in Git keeps changing as more code is added. Also, many developers can add code in parallel. So Version Control System helps in handling this by maintaining a history of what changes have happened. Also, Git provides features like branches and merges.
Distributed Version Control System: Git has a remote repository which is stored in a server and a local repository which is stored in the computer of each developer. This means that the code is not just stored in a central server, but the full copy of the code is present in all the developers’ computers.

Why Git is needed?

Real life projects generally have multiple developers working in parallel. So a version control system like Git is needed to ensure there are no code conflicts between the developers. Additionally, the requirements in such projects change often. So a version control system allows developers to revert and go back to an older version of the code. Finally, sometimes several projects which are being run in parallel involve the same codebase. In such a case, the concept of branching in Git is very important.

Download Git

Download Git

Instaling Git

Installing Git

Know more about Git

Atlassian Tutorial

Bash Script

#!/bin/bash

for branch in $(git branch -r --merged | grep -v HEAD | grep -v develop | grep -v master | grep -v feature/develop | sed /\*/d); do
    remote_branch=$(echo $branch | sed 's#origin/##')
    git push origin --delete $remote_branch
done

Notice for this case that you should have access to the repository with an ssh key private/public pair. To use, this script you should stand in the root directory of the local repository and run it, be careful, look well what remote branch you do not want to delete and add it to the filter grep -v.

Notice too that you may delete all types of branches, not only merged, if you delete the flag --merged from the script you delete open branches too.

Code

Github