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?
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
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.
(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_".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With