Git: Repository clean-up

This blog post describes how to delete obsolete branches, which were already merged.

René Kulik on 08.07.2017

Especially in large projects with several programmers involved, there is a lot of activity inside the git repository. Features get opened/closed or release branches get merged into master without deleting the corresponding branches. During this processes corresponding branches may not be deleted which ends up in a messy repository.

This blog post describes how to easily delete these obsolete branches.

The goal is to delete all branches which were already merged to master. To accomplish this, we switch to the master branch:

git checkout master

After that we run the following command, which deletes the obsolete branches:

git branch --merged master | grep -v "\* master" | xargs -n 1 git branch -d

Your console should look like this after running the command:

Deleted branch feature/foo
Deleted branch feature/bar

Et voilà! We cleaned our git repository. But what exactly happend? Let’s take a closer look.

git branch --merged master

This part returns a list of branches, which were already merged into master.

grep -v "\* master"

With the aid of this command, we grep all branches from the list which do not begin with * master.

xargs -n 1 git branch -d

xargs is a Unix program used to build and execute command lines from standard input. In our case it executes git branch -d for every branch from the list. This command deletes the branches. By providing the option -n 1 we limit the amount of arguments to 1. This ensures that only the branch name gets passed to the delete command.