是否有一种简单的方法可以删除所有远程对等分支不再存在的跟踪分支?

例子:

分支机构(本地和远程)

主人原始/主起源/bug-fix-a起源/bug-fix-b起源/bug-fix-c

在本地,我只有一个主分支。现在我需要处理bug-fix-a,所以我检查它,处理它,并将更改推到远程。接下来,我对bug-fix-b做同样的操作。

分支机构(本地和远程)

主人bug-fix-abug-fix-b型原始/主起源/bug-fix-a起源/bug-fix-b起源/bug-fix-c

现在我有本地分支机构master,bug-fix-a,bug--fix-b。主分支维护者将把我的更改合并到主分支中,并删除他已经合并的所有分支。

因此,当前状态为:

分支机构(本地和远程)

主人bug-fix-abug-fix-b型原始/主起源/bug-fix-c

现在我想调用一些命令来删除分支(在本例中为bug-fix-a、bug-fix-b),这些分支在远程存储库中不再表示。

它类似于现有命令git remote prune origin,但更类似于git local prune origin。


当前回答

你可以这样做:

git branch -vv | grep 'origin/.*: gone]' | awk '{print $1}' | xargs git branch -d

附笔。:正如Sam H。

首先执行以下操作:

git remote prune origin

其他回答

所有这些都不适合我。我想要一些东西来清除所有跟踪远程分支的本地分支,在源位置,远程分支已被删除(消失)。我不想删除从未设置为跟踪远程分支的本地分支(即:我的本地dev分支)。我还想要一个简单的一行程序,它只使用git或其他简单的CLI工具,而不是编写自定义脚本。我最后使用了一点grep和awk来生成这个简单的命令。

这最终是我的~/.gitconfig:

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

这里有一个git-config--global。。。用于轻松将其添加为git prune分支的命令:

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

注意:在config命令中,我使用-d选项来gitbranch,而不是-d,正如我在实际配置中所做的那样。我使用-D是因为我不想听到Git抱怨未合并的分支。您可能也需要此功能。如果是这样,只需在config命令末尾使用-D而不是-D。

这里的答案似乎都不适合我,或者完全按照我的意愿(删除本地分支,而不是远程分支)。所以我写了这篇文章,虽然有点拗口,但很管用。

touch /tmp/remote-refs && touch /tmp/local-refs && touch /tmp/diff-refs;
while shortened=$(git for-each-ref refs/remotes) && echo ${${shortened}//"\/remotes\/origin"} > /tmp/remote-refs &&
shortened=$(git for-each-ref refs/heads | grep -v "master\|develop") && echo ${${shortened}//"\/heads"} > /tmp/local-refs &&
diff=$(comm -13 /tmp/remote-refs /tmp/local-refs) && echo ${${diff}##*refs/} > /tmp/diff-refs &&
xargs git branch -D </tmp/diff-refs; do :; done

只需确保首先运行git remote prune origin

我不确定要用多久,但我现在确实使用git-up,这可以解决这个问题。

我做了git,它开始跟踪新的分支并删除旧的分支。

为了清楚起见,这不是现成的git命令-https://github.com/aanand/git-up

顺便说一句,它还藏着脏树,只需把它捡起来就可以重新放回原处。

希望对某人有用

我喜欢使用管道,因为它使命令更容易阅读。

如果您想删除除master之外的所有分支,这是我的解决方案。

git branch | grep -v master | xargs -n 1 git branch -D

要删除符合条件的其他分支,请修改第一个和第二个块。

git branch --merged | grep feature_name | xargs -n 1 git branch -D

基于Git提示:删除旧的本地分支,这看起来类似于jason.rickman的解决方案。为此,我使用Bash实现了一个名为Git-gone的自定义命令:

$ git gone
usage: git gone [-pndD] [<branch>=origin]
OPTIONS
  -p  prune remote branch
  -n  dry run: list the gone branches
  -d  delete the gone branches
  -D  delete the gone branches forcefully

EXAMPLES
git gone -pn    prune and dry run
git gone -d     delete the gone branches

git gone-pn结合了修剪和列出“goned”分支:

$ git gone -pn
  bport/fix-server-broadcast         b472d5d2b [origin/bport/fix-server-broadcast: gone] Bump modules
  fport/rangepos                     45c857d15 [origin/fport/rangepos: gone] Bump modules

然后,您可以使用git-gone-d或git-gone-d来扣动扳机。

笔记

我使用的正则表达式是“$BRANCH/.*:gone]”,其中$BRANCH通常是源代码。如果您的Git输出本地化为法语等,这可能不会起作用。Sebastian Wiesner还为Windows用户将其移植到Rust。那个也叫git gone。