Easily Clean Up Your Git Branches

A Simple Guide to Remove All Branches Except Master/Main

Play this article


In this blog post, I'll share a quick Git tip to help you keep your repositories clean and organized. If you have a Git repository with many branches, it can be useful to remove all branches except the main or master branch. Let's dive into the steps to achieve this.

Step 1: Navigate to the Git Repository

Open your terminal and navigate to the Git repository you want to clean up.

Step 2: Execute the Clean-up Command

Run the following command:

git branch | grep -v "main\|master" | xargs -p git branch -D

You will see the output below

git branch -D test test2?...

Press 'y' and hit enter if you are satisfied with the execution plan. Then, git branch -D will be executed:

git branch -D test test2?...y
Deleted branch test (was ac8a396).
Deleted branch test2 (was ac8a396).

Understanding the Command

Let's break down the command step by step:

git branch

This command lists all branches. Assume you have three branches: main, test, and test2. You will see the output below:

* main

grep -v

grep is a command used to search plain-text data that matches a regular expression. With -v, it excludes the main and master branches from the output.

xargs -p git branch -D

xargs is a command used to build and execute commands from standard input. In this case, its input comes from grep -v, which is a list of branches excluding main and master. The -p argument allows you to review the execution and decide whether to continue.


By removing unnecessary branches, you can keep your Git repository organized and improve your workflow. Give it a try! Let us know if you have any questions or suggestions in the comments below.