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

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

我该怎么做呢?


当前回答

使用@wisbucky答案的变体,我将以下内容作为~/的别名添加到~/。gitconfig文件:

pruneitgood = "!f() { \
    git remote prune origin; \
    git branch -vv | perl -nae 'system(qw(git branch -d), $F[0]) if $F[3] eq q{gone]}'; \
}; f"

这样,一个简单的git pruneitgood就可以清理合并后不再需要的本地和远程分支。

其他回答

如果要删除所有已经合并到master中的本地分支,可以使用以下命令:

git branch --merged master | grep -v '^[ *]*master$' | xargs git branch -d

如果你使用main作为你的主分支,你应该相应地修改命令:

git branch --merged main | grep -v '^[ *]*main$' | xargs git branch -d

更多信息。

删除所有没有更新到master的分支

git co master && git branch | sed s/\*/\ / | xargs git branch -d 2> /dev/null

以下是@wisbucky对Windows用户的回答:

for /f "tokens=1" %i in ('git branch -vv ^| findstr ": gone]"') DO git branch %i -d

我使用posh-git,不幸的是PS不喜欢裸体for,所以我创建了一个普通的'ol命令脚本,名为PruneOrphanBranches.cmd:

@ECHO OFF
for /f "tokens=1" %%i in ('git branch -vv ^| findstr ": gone]"') DO CALL :ProcessBranch %%i %1

GOTO :EOF

:ProcessBranch
IF /I "%2%"=="-d" (
    git branch %1 %2
) ELSE (
    CALL :OutputMessage %1
)
GOTO :EOF

:OutputMessage
ECHO Will delete branch [%1] 
GOTO :EOF

:EOF

不带参数调用它以查看列表,然后用“-d”调用它来执行实际的删除或对任何没有完全合并但无论如何都想删除的分支执行“-d”。

基于以上的答案,我想出了这个简单的解决方案:

git remote prune origin; git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk '{print $1}' | xargs git branch -d

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。