Git BASH delete all local branches matching a pattern

Viewed 75

I was trying to create a branch by the name test/miwarren/memberLead, but had orphan local branches (i.e. branches that were merged and then deleted on remote), which prevented that:

$ git checkout -b test/miwarren/memberLead
fatal: cannot lock ref 'refs/heads/test/miwarren/memberLead': 'refs/heads/test/miwarren/memberLead/dob' exists; cannot create 'refs/heads/test/miwarren/memberLead'

I created branch for each member lead test sub-suite that I was working on at the time.

How to find and delete them all, so that I can create my branch?

2 Answers

The line of code that's going to get the job done

Assuming that you have no other branches that match that pattern, that you need, on local or remote, you can just say:

git for-each-ref --format='%(refname:lstrip=2)' 'refs/heads/test/miwarren/memberLead/*' | xargs git branch -d

To anyone reading this to apply this to your situation, make sure to replace test/miwarren/memberLead with the name of your branch, on which you face issue when trying to create! This work iff the branch you're trying to create is substring of the orphan branches that are giving you issue.

Explanation

We get the list of refs that match the pattern 'refs/heads/[your_branch_name]' with git for-each-ref, and map it to branch name, on the left-hand side, and then pipe that to git branch -d on the right-hand side.

Left-hand side of it

git for-each-ref 'refs/heads/[your_branch_name], out of the box, returns all the refs that match the specified pattern. The --format='%(refname:lstrip=2)' flag tells that command "format the output, by stripping the first two words from it". Surprise, surprise, the output equals the branch names.

Right hand side of it

Not much going on. Here's the official description of xargs. git branch -d [your_branch_name] deletes the branch [your_branch_name].

Use this command

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.

Reference

https://www.seancdavis.com/blog/git-delete-multiple-local-branches/

Related