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

后端 未结 6 1958
暖寄归人
暖寄归人 2021-01-30 09:21

At work we are using topic branches which are integrated into a few (3) master branches at some point. Now I\'d like to delete all topic branches from my remote reposit

6条回答
  •  生来不讨喜
    2021-01-30 09:43

    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

提交回复
热议问题