使用git远程修剪原点,我可以删除不在远程上的本地分支。

但是我还想删除从这些远程分支创建的本地分支(检查它们是否未合并会很好)。

我该怎么做呢?


当前回答

您可以使用该命令:

git branch --merged master | grep -v "\* master" | xargs -n 1 git branch -d

Git清洁:删除已经合并的分支,包括分解命令

其他回答

I wanted something that would purge all local branches that were tracking a remote branch, on origin, where the remote branch has been deleted (gone). I did not want to delete local branches that were never set up to track a remote branch (i.e.: my local dev branches). Also, I wanted a simple one-liner that just uses git, or other simple CLI tools, rather than writing custom scripts. I ended up using a bit of grep and awk to make this simple command, then added it as an alias in my ~/.gitconfig.

[alias]
  prune-branches = !git remote prune origin && git branch -vv | grep ': gone]' | awk '{print $1}' | xargs -r git branch -D

这是一个git配置-全局…命令可以方便地将其添加为git prune-branches:

git config --global alias.prune-branches '!git remote prune origin && git branch -vv | grep '"'"': gone]'"'"' | awk '"'"'{print $1}'"'"' | xargs -r git branch -d'

注意:对git分支使用-D标志可能非常危险。所以,在上面的config命令中,我使用-d选项来git分支而不是-d;我在实际配置中使用-D。我使用-D是因为我不想听到Git抱怨未合并的分支,我只是想让它们消失。您可能也需要这个功能。如果是这样,只需在配置命令的末尾使用-D而不是-D。

Windows的解决方案

适用于Microsoft Windows Powershell:

Git结帐大师;Git远程更新源——prune;git branch -vv | Select-String -Pattern ": gone]" | % {$_.toString(). trim()。Split(" ")[0]} | % {git branch -d $_}

解释

Git签出主切换到主分支

Git远程更新来源——修剪远程分支

Git分支-vv获取所有分支的详细输出(Git引用)

Select-String -Pattern ": gone]"只获取已从远程删除的记录。

% {$_.toString()。Split(" ")[0]}获取分支名称

% {git branch -d $_}删除分支

你可以通过一些简单的操作来做到这一点:

输出你所有的分支到一个临时文件:

git branch > branches.tmp

打开文件并删除分支以排除它们从本地删除(分支如develop/master/main/…) 通过cat命令将分支名称传递给xargs并删除分支:

cat branches.tmp | xargs git branch -D

基于上面的答案,我使用了更短的一行:

git remote prune origin | awk 'BEGIN{FS="origin/"};/pruned/{print $2}' | xargs -r git branch -d

此外,如果你已经修剪过了,并且有局部的树枝悬挂着,那么这将清理它们:

git branch -vv | awk '/^ .*gone/{print $1}' | xargs -r git branch -d

除了Schleis的答案(它工作得很完美),它还可以集成到Visual Studio中,所以在VS中打开git repo时修剪本地分支非常简单。

您可以使用外部工具功能调用sh.exe (git bash)与特定的目录和命令。它位于工具>外部工具菜单选项中(在VS 2022 17.1.0中)。我使用的参数如下:

命令:{Path-To-Git-Installation-Location} \ bin \ sh.exe

参数:——cd=$(SolutionDir) -c "git fetch -p;Git branch -r | awk '{print $1}' | egrep -v -f /dev/ fg /0 <(Git branch -vv | grep origin) | awk '{print $1}' | xargs Git branch -d"

初始目录:$(SolutionDir)

Git修剪本地分支的截图

值得注意的是,只有当你在VS中打开的解决方案在git repo目录中时,这才会起作用。

最后提醒-这可以通过Visual Studio的按键绑定用户界面在设置>通用>键盘和搜索工具进行按键绑定。ExternalCommand[n],其中n是外部命令表中的位置,您有这个外部工具的位置(它们可以在工具>外部工具对话框中重新排序)。请看下面的截图。

键盘绑定外部工具命令