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


当前回答

截至2018.07

将其添加到~/.gitconfig的[alias]部分:

sweep = !"f() { git branch --merged | egrep -v \"(^\\*|master|dev)\" || true | xargs git branch -d; }; f"

现在,您只需调用git扫描来执行所需的清理。

其他回答

以下查询适用于我

for branch in  `git branch -r --merged | grep -v '\*\|master\|develop'|awk 'NR > 0 {print$1}'|awk '{gsub(/origin\//, "")}1'`;do git push origin --delete $branch; done

这将过滤grep管道中的任何给定分支。

在http克隆上运行良好,但在ssh连接上运行不太好。

Windoze友好的Python脚本(因为git sweep阻塞了Wesnoth存储库):

#!/usr/bin/env python
# Remove merged git branches. Cross-platform way to execute:
#
#   git branch --merged | grep -v master | xargs git branch -d
#
# Requires gitapi - https://bitbucket.org/haard/gitapi
# License: Public Domain

import gitapi

repo = gitapi.Repo('.')
output = repo.git_command('branch', '--merged').strip()
for branch in output.split('\n'):
  branch = branch.strip()
  if branch.strip(' *') != 'master':
    print(repo.git_command('branch', '-d', branch).strip())

https://gist.github.com/techtonik/b3f0d4b9a56dbacb3afc

git工具箱中的git清理脚本

删除所有已合并到主或发展让其他树枝到处乱放。删除时最保守。删除本地和源远程中的分支。

如果您想删除已合并到当前所在分支的所有本地分支,那么我根据前面的回答提出了一个安全的命令:

git branch --merged | grep -v \* | grep -v '^\s*master$' | xargs -t -n 1 git branch -d

此命令不会影响当前分支或主分支。它还将使用xargs的-t标志告诉您它在做什么。

如果您使用的是Windows,您可以使用Windows Powershell或Powershell 7以及Out GridView来创建一个漂亮的分支列表,并用鼠标选择要删除的分支:

git branch --format "%(refname:short)" --merged  | Out-GridView -PassThru | % { git branch -d $_ }

单击“确定”后,Powershell会将这些分支名称传递给gitbranch-d命令并删除它们