Can you delete multiple branches in one command with Git?

I'd like to clean up my local repository, which has a ton of old branches: for example 3.2, 3.2.1, 3.2.2, etc.

I was hoping for a sneaky way to remove a lot of them at once. Since they mostly follow a dot release convention, I thought maybe there was a shortcut to say:

git branch -D 3.2.*

and kill all 3.2.x branches.

I tried that command and it, of course, didn't work.


Solution 1:

Not with that syntax. But you can do it like this:

git branch -D 3.2 3.2.1 3.2.2

Basically, git branch will delete multiple branch for you with a single invocation. Unfortunately it doesn't do branch name completion. Although, in bash, you can do:

git branch -D `git branch | grep -E '^3\.2\..*'`

Solution 2:

Well, in the worst case, you could use:

git branch | grep '3\.2' | xargs git branch -D

Solution 3:

You can use git branch --list to list the eligible branches, and use git branch -D/-d to remove the eligible branches.

One liner example:

git branch -d `git branch --list '3.2.*'`

Solution 4:

git branch  | cut -c3- | egrep "^3.2" | xargs git branch -D
  ^                ^                ^         ^ 
  |                |                |         |--- create arguments
  |                |                |              from standard input
  |                |                |
  |                |                |---your regexp 
  |                |
  |                |--- skip asterisk 
  |--- list all 
       local
       branches

EDIT:

A safer version (suggested by Jakub Narębski and Jefromi), as git branch output is not meant to be used in scripting:

git for-each-ref --format="%(refname:short)" refs/heads/3.2\* | xargs git branch -D

... or the xargs-free:

git branch -D `git for-each-ref --format="%(refname:short)" refs/heads/3.2\*`