How to delete all remote git branches except master#

If you working on a big collaborative project using git, the repo's remote will quickly accumulate branches from all the contributors. And very soon there will be big list of branches on remote.

It is a good practice to delete a branch once it has landed on master. But that is easier said, than done. Many remote branches linger on for whatever reasons. Here is a quick method for deleting all the remote git branches except master.

First, we will do some configuration, where we set the name of the remote and the "master" branch.

For this example, we are assuming the typical defaults - remote is named origin, the "master" branch is named master. If their values are different for your repo, make sure to use the right values.

$ REMOTE="origin" && MASTER="master"

Then execute this command:

$ git branch -r |  grep "^  ${REMOTE}/" | sed "s|^  ${REMOTE}/|:|" | grep -v "^:HEAD" | grep -v "^:${MASTER}$" | xargs echo

Well, that doesn't actually delete the remote branches. It shows you the branches that will be delete. This is your last chance to change your mind or make any changes.

This is the command to delete all the branches except master, on your remote Git repository. Do not run this command unless you really want to delete all your branches, except the one set in MASTER.

$ git branch -r |  grep "^  ${REMOTE}/" | sed "s|^  ${REMOTE}/|:|" | grep -v "^:HEAD" | grep -v "^:${MASTER}$" | xargs git push ${REMOTE}

So, how does this command work?

  1. git branch -r - lists all the remote branches
  2. grep "^ ${REMOTE}/" - filters remote branches from origin, a repo can have more than one remote
  3. sed "s|^ ${REMOTE}/|:|" - exctracts the branch names and prepare them for deletion by prepend them with :
  4. grep -v "^:HEAD" - filters out invalid branch name which was generated as a side-effect in step 3
  5. grep -v "^:${MASTER}$" - filters out master, excluding it from the deletion list
  6. xargs git push ${REMOTE} - executes the branch deletion command on remote named origin with the list of branches which made through the filter

There are two syntaxes for deleting remote branches: git push <remote> --delete <branch1[, branch2, ...]> and git push <remote> :<branch1[, branch2, ...]>. The latter syntax was used for the example, you can achive the same effect using the former syntax with some customization.

Summary#

git doesn't have a command to delete all the remote branches with exceptions. However, the task can be accomplished by setting some variables and piping git branch -r, grep, sed, and xargs git push.

References#

  1. Git - git-branch
  2. WikiPedia - grep
  3. WikiPedia - xargs
  4. WikiPedia - Pipeline (Unix)
  5. WikiPedia - Sed
  6. Git: Delete all local branches except master
Tweet this | Share on LinkedIn |