Git: Delete all remote branches except master
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.
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?
git branch -r
- lists all the remote branchesgrep "^ ${REMOTE}/"
- filters remote branches fromorigin
, a repo can have more than one remotesed "s|^ ${REMOTE}/|:|"
- exctracts the branch names and prepare them for deletion by prepend them with:
grep -v "^:HEAD"
- filters out invalid branch name which was generated as a side-effect in step 3grep -v "^:${MASTER}$"
- filters outmaster
, excluding it from the deletion listxargs git push ${REMOTE}
- executes the branch deletion command on remote namedorigin
with the list of branches which made through the filter
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#
- Git - git-branch
- WikiPedia - grep
- WikiPedia - xargs
- WikiPedia - Pipeline (Unix)
- WikiPedia - Sed
- Git: Delete all local branches except master