如何删除所有已合并的 Git 分支? [英] How can I delete all Git branches which have been merged?

查看:37
本文介绍了如何删除所有已合并的 Git 分支?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多 Git 分支.如何删除已经合并的分支?有没有一种简单的方法可以把它们全部删除而不是一个一个地删除它们?

I have many Git branches. How do I delete branches which have already been merged? Is there an easy way to delete them all instead of deleting them one by one?

推荐答案

更新:

如果您的工作流程将其他分支作为可能的祖先,则您可以添加其他分支以排除像 master 和 dev 这样的分支.通常我从sprint-start"分支开始tag 和 master,dev 和 qa 不是祖先.

You can add other branches to exclude like master and dev if your workflow has those as a possible ancestor. Usually I branch off of a "sprint-start" tag and master, dev and qa are not ancestors.

首先,列出在远程合并的本地跟踪分支(您可以考虑使用 -r 标志列出其他答案中建议的所有远程跟踪分支).

First, list locally-tracking branches that were merged in remote (you may consider to use -r flag to list all remote-tracking branches as suggested in other answers).

git branch --merged

您可能会看到一些不想删除的分支.我们可以添加一些参数来跳过我们不想删除的重要分支,如 master 或 develop.以下命令将跳过 master 分支和其中包含 dev 的任何内容.

You might see few branches you don't want to remove. we can add few arguments to skip important branches that we don't want to delete like master or a develop. The following command will skip master branch and anything that has dev in it.

git branch --merged| egrep -v "(^*|master|main|dev)"

如果想跳过,可以像下面这样添加到 egrep 命令中.分支 skip_branch_name 不会被删除.

If you want to skip, you can add it to the egrep command like the following. The branch skip_branch_name will not be deleted.

git branch --merged| egrep -v "(^*|master|main|dev|skip_branch_name)"

删除所有已经合并到当前签出分支的本地分支:

To delete all local branches that are already merged into the currently checked out branch:

git branch --merged | egrep -v "(^*|master|main|dev)" | xargs git branch -d

您可以看到 master 和 dev 被排除在外,以防它们是祖先.

You can see that master and dev are excluded in case they are an ancestor.

您可以删除合并的本地分支:

You can delete a merged local branch with:

git branch -d branchname

如果未合并,请使用:

git branch -D branchname

从远程使用中删除它:

git push --delete origin branchname

git push origin :branchname    # for really old git

一旦你从远程删除分支,你可以修剪以摆脱远程跟踪分支:

Once you delete the branch from the remote, you can prune to get rid of remote tracking branches with:

git remote prune origin

或修剪单个远程跟踪分支,正如另一个答案所暗示的那样:

or prune individual remote tracking branches, as the other answer suggests, with:

git branch -dr branchname

这篇关于如何删除所有已合并的 Git 分支?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆