Delete All Git Branch Except 1 With Bash Script

Ridho perdana
Jul 13 · 2 min read

When coding a project in a team, having multiple branches of Git repository is unavoidable, and later it’ll make our workspace bloated with branches that we don’t use anymore.

Image for post
Photo by Thought Catalog on Unsplash

Deleting a single local Git branch in our machine is quite simple:

git branch -D <branch_name>

But if we have more than 10 branches (which is very possible) repeating that command is a bad choice and takes time. Then I search the internet about the git command on how to delete all branches except the master.

Why the master branch? Because the default root branch in Git is master and many programmers use the code inside it as the base code before deploying the application. And here’s what I found:

git branch | grep -ve " master$" | xargs git branch -D

That command is consists of multiple commands that produce multiple results, there are:

  1. List all branch’s name that has a prefix of master
  2. Take all that branch’s name and pass it as the argument into
    git branch -D command.

I tried the command and it works flawlessly, but it got 1 problem. It is the name of the branch. I think we as a programmer will sometime need to delete all existing branches including the master, but excluding the other name.

So I decided to create a simple bash script to run a git command, which can delete all branches except 1 branch.

The script is simple, it’s only taking a single argument that will replace the branch name inside the git command.

Here is the script:

To run the script you just need to type:

./ <branch_name>

Simple right?

If you want to view the complete script, that has a help page, you can see it from my repo:

Have a nice day! 🖖


Easy read, easy understanding.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store