Delete Multiple Local Git Branches

Learn how to use a single command to delete multiple git branches.

Ever get yourself caught in a situation where you have a whole mess of branches and you want to get cleaned up?

The process is actually quite simple. All you need is some regular expression pattern to target the branch names, and then you sweep through them.

The command looks like this:

$ git branch | grep [PATTERN] | xargs git branch -D

These are three commands piped together. Here's how they work:

  1. git branch prints a list of branches. It precedes the current branch with an asterisk.
  2. grep [PATTERN] searches the list and returns those lines that match the pattern.
  3. xargs gives us the returned list from grep, and then we pass those to git branch -D, which deletes the branch.

Test It First

It can come in handy to give the first two commands a whirl so you know what you're going to delete. For example, to see a list of all branches, excluding the current branch, you could run this command:

$ git branch | grep "^[ ]"

Establish a Pattern

Having a pattern for how you name branches can come in handy when cleaning up like this. For example, I often precede branches with a number when they are addressing a specific issue. To provide a list of branches that begin with a number, I can run this command:

$ git branch | grep "^[ ]\+\d"



There are two things to look out for here:

  1. I'm using the -D flag for git branch, which is an alias for --delete --force. If you don't want to force delete, you can use the -d flag instead.
  2. There are two spaces at the beginning of every branch in the list that isn't your current branch. When searching for the beginning of a string, don't forget about these spaces. That always seems to trip me up.

Let's Connect

Keep Reading

Safely Force Pushing in Git

If force-pushing is part of your git workflow, here's a tip that can help you avoid disaster.

Jul 22, 2021

Is GitHub the Best CMS?

It seems like a silly question, given that GitHub is not typically thought about as a CMS. But I analyze the question anyways, using a series of 11 factors.

Aug 30, 2022

Git Checkout Previous Branch

Checkout the previous git branch without needing to remember or type the name.

Jul 27, 2022