Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete large number of branches from remote

I have a Git remote that has 1000 branches, and I want to delete all the branches whose name does not start with foo_. Is there an easy way to do that?

like image 284
Ram Rachum Avatar asked Mar 12 '23 07:03

Ram Rachum


1 Answers

Short answer

If your remote is called "origin", run

git for-each-ref --format='%(refname:strip=3)' refs/remotes/origin/* | \
  grep -v '^foo_\|^HEAD$' | \
  xargs git push --delete origin

More details

Prefer git for-each-ref over git branch

The other answers suggest piping the output of git branch to grep or awk. However, such an approach is brittle: git branch is a Porcelain (i.e. high-level) command, whose output may change in a future Git release. A better alternative is to use git for-each-ref, a powerful Plumbing (i.e. low-level) command.

Explanation of the command

(Note: the following assumes that your remote is called "origin".)

Use git for-each-ref to list all the remote branches on origin in an adequate format:

git for-each-ref --format='%(refname:strip=3)' refs/remotes/origin/*

Pipe the output to

grep -v '^foo_\|HEAD$'

to discard HEAD and all the branches whose name starts with "foo_". Finally, pipe the output to

xargs git push --delete origin

to delete all the relevant remote branches from origin in one fell swoop.

Caveat: Of course, the command above won't be able to delete current branch of the remote if the latter doesn't start with "foo_".

like image 112
jub0bs Avatar answered Mar 16 '23 08:03

jub0bs