我遵循一个开发过程,即为每个新功能或故事卡创建一个新的本地分支。完成后,我合并到主分支,然后推。

随着时间的推移,由于懒惰或健忘,我最终会得到一个很大的本地分支列表,其中一些(如spike)可能还没有合并。

我知道如何列出我所有的本地分支,我知道如何删除一个分支,但我想知道是否有一个git命令,允许我删除我所有的本地分支?

下面是git分支——merged命令的输出。

user@machine:~/projects/application[master]$ git branch --merged
  STORY-123-Short-Description
  STORY-456-Another-Description
  STORY-789-Blah-Blah
* master

所有尝试删除grep -v \*列出的分支(根据下面的答案)都会导致错误:

error: branch 'STORY-123-Short-Description' not found.
error: branch 'STORY-456-Another-Description' not found.
error: branch 'STORY-789-Blah-Blah' not found.

我用的是:

git 1.7.4.1  
ubuntu 10.04  
GNU bash, version 4.1.5(1)-release  
GNU grep 2.5.4  

当前回答

要删除除当前已签出的分支之外的所有分支:

for b in `git branch --merged | grep -v \*`; do git branch -D $b; done

我建议在前几次将git branch -D $b更改为echo $b,以确保它删除了你想要的分支。

其他回答

对于powershell,这将工作:

git branch --format '%(refname:lstrip=2)' --merged `
    | Where-Object { $_ -ne 'master' } `
    | ForEach-Object { git branch -d $_ }

如果你使用NodeJS,我写了这个命令:

npx git-clear-branch

该命令清除除master和当前分支之外的所有本地分支。

首先(切换到你想要保留> ex: master的分支):

git checkout master

第二(确保你在master上)

git branch -D $(git branch)

如果您正在使用PowerShell,请使用

git branch -D $(git branch).Trim()

下面是适用于Windows机器的Powershell解决方案

git checkout master # by being on the master branch, you won't be able to delete it
foreach($branch in (git branch))
{
    git branch -D $branch.Trim()
}

提醒一下,我会升级到git 1.7.10。你可能在这里得到的答案并不适用于你的版本。我的猜测是你必须在分支名称前加上refs/heads/。

注意,只有在复制了工作文件夹和.git目录后,才能继续执行以下操作。

我有时直接从。git/refs/heads中删除我不想要的分支。所有这些分支都是文本文件,包含它们所指向的提交的40个字符sha-1。如果你为其中任何一个设置了特定的跟踪,你的.git/配置中将会有多余的信息。您也可以手动删除这些条目。