How to delete all remote git branches which have already been integrated?

If you want to delete remote branches from origin repository:

git branch -r --merged develop | egrep -iv '(master|develop)' | sed 's/origin\///g' | xargs -n 1 git push --delete origin

You can do this in one go with

git branch --merged master | grep -v master | xargs -n 1 git push --delete origin

Dump that in a script called 'clean' if you find you're doing this often.


Another answer edited in by someone who thought it's the best (and it looks good):

git branch -r --merged origin/master | grep -v master | grep "origin/" | cut -d "/" -f 2- | xargs -n 20 git push --delete origin

Explanation:

  • git branch -r --merged origin/master
    • -r/--remotes list the remote-tracking branches.
    • --merged origin/master only list branches whose tips are reachable from origin/master.
  • grep -v master remove any branch name containing master from list.1-v means negative match.
  • grep "origin/" select only branches on origin remote.
  • cut -d "/" -f 2- drop the origin/ prefix
  • xargs -n 20 git push --delete origin do something similar to git push --delete origin branch-a branch-b branch-c …
    • -n 20/--max-args=20 use at most 20 arguments per command line.

As for -n, I choose 20 just as an example. Fewer arguments will make it slower, for example -n 1 makes it delete one at a time; you have more progress hints, because it will report each time it deletes a branch. More arguments like -n 200 will make it faster (less total time), but it only reports once every 200 branches, making you think that it is frozen at first (while it is not). Tune the number to your need. If you omit this option, the default number is really large (2048 in my machine).

1. Note that this also removes origin/HEAD -> origin/master, but you won't want to mess with origin/HEAD anyway.

Original answer:

git push --delete remote topicbranch

or

git push remote :topicbranch

Giving a list of branches, would be something with git branch --merged master

Tags:

Git

Git Branch