如何删除已合并的分支?我可以一次删除所有分支,而不是逐个删除每个分支吗?


当前回答

刚刚为此创建了python脚本:

import sys
from shutil import which
import logging
from subprocess import check_output, call

logger = logging.getLogger(__name__)

if __name__ == '__main__':
    if which("git") is None:
        logger.error("git is not found!")
        sys.exit(-1)

    branches = check_output("git branch -r --merged".split()).strip().decode("utf8").splitlines()
    current = check_output("git branch --show-current".split()).strip().decode("utf8")
    blacklist = ["master", current]

    for b in branches:
        b = b.split("/")[-1]

        if b in blacklist:
            continue
        else:
            if input(f"Do you want to delete branch: '{b}' [y/n]\n").lower() == "y":
                call(f"git branch -D {b}".split())
                call(f"git push --delete origin {b}".split())

其他回答

您需要从这些命令中排除master、main和develop分支。

本地git清除:

git branch --merged | grep -v '\*\|master\|main\|develop' | xargs -n 1 git branch -d

远程清零:

git branch -r --merged | grep -v '\*\|master\|main\|develop' | sed 's/origin\///' | xargs -n 1 git push --delete origin

同步远程分支的本地注册表:

git fetch -p

要删除合并的分支,gitdelete合并的分支比shell黑客更健壮、更方便。它还检测重基合并和挤压合并。它的自述文件有更多细节。

公认的解决方案很好,但有一个问题,它还删除了尚未合并到远程的本地分支。

如果你查看的输出,你会看到

$ git branch --merged master -v
  api_doc                  3a05427 [gone] Start of describing the Java API
  bla                      52e080a Update wording.
  branch-1.0               32f1a72 [maven-release-plugin] prepare release 1.0.1
  initial_proposal         6e59fb0 [gone] Original proposal, converted to AsciiDoc.
  issue_248                be2ba3c Skip unit-for-type checking. This needs more work. (#254)
  master                   be2ba3c Skip unit-for-type checking. This needs more work. (#254)

分支bla和issue_248是将被默默删除的本地分支。

但您也可以看到单词[gone],它表示已被推到远程(现在已不存在)的分支,因此表示可以删除分支。

因此,原始答案可以更改为(拆分为多行以缩短行长度)

git branch --merged master -v | \
     grep  "\\[gone\\]" | \
     sed -e 's/^..//' -e 's/\S* .*//' | \
      xargs git branch -d

以保护尚未合并的分支。此外,也不需要为master提供保护,因为它在源位置有一个远程,不会显示为已删除。

要删除已合并到主分支的本地分支,我使用以下别名(git-config-e--global):

cleanup = "!git branch --merged master | grep -v '^*\\|master' | xargs -n 1 git branch -D"

我使用gitbranch-D来避免错误:分支“somebranch”未完全合并。消息,而我的当前签出与主分支不同。

您可以使用git del br工具。

git-del-br -a

您可以使用pip安装它

pip install git-del-br

P.S:我是这个工具的作者。欢迎提出任何建议/反馈。