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

随着时间的推移,由于懒惰或健忘,我最终会得到一个很大的本地分支列表,其中一些(如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  

当前回答

以上答案很好。这是另一种方法,当我们在本地回购中有很多分支时,我们必须删除许多分支,除了少数位于本地机器中的分支。

第一个git分支将列出所有本地分支。

运行unix命令将一列分支名称转换为文件中的单行 Git分支> sample.txt 这将保存在sample.txt文件中。 和运行 awk 'BEGIN {ORS = " "} {print}' sample.txt 命令。这将把列转换为行,并在单行中复制分支名称列表。

然后运行git branch -D branch_name(s)。这将删除在local中列出的所有分支

其他回答

我发现使用文本编辑器和shell更容易。

在shell中输入git checkout <TAB>。将显示所有本地分支。 复制它们到文本编辑器,删除那些你需要保留。 用空格替换换行。(在SublimeText中,这非常简单。) 打开shell,输入git branch -D <PASTE THE BRANCHES NAMES HERE>。

就是这样。

'git branch -d'子命令可以删除多个分支。所以,简化@sblom的答案,但增加了一个关键的xargs:

git branch -D `git branch --merged | grep -v \* | xargs`

或者,进一步简化为:

git branch --merged | grep -v \* | xargs git branch -D 

重要的是,正如@AndrewC所指出的,不鼓励使用git分支来编写脚本。要避免使用,可以使用如下语句:

git for-each-ref --format '%(refname:short)' refs/heads | grep -v "master\|main" | xargs git branch -D

删除时要谨慎!

$ mkdir br
$ cd br; git init
Initialized empty Git repository in /Users/ebg/test/br/.git/
$ touch README; git add README; git commit -m 'First commit'
[master (root-commit) 1d738b5] First commit
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 README
$ git branch Story-123-a
$ git branch Story-123-b
$ git branch Story-123-c
$ git branch --merged
  Story-123-a
  Story-123-b
  Story-123-c
* master
$ git branch --merged | grep -v \* | xargs
Story-123-a Story-123-b Story-123-c
$ git branch --merged | grep -v \* | xargs git branch -D
Deleted branch Story-123-a (was 1d738b5).
Deleted branch Story-123-b (was 1d738b5).
Deleted branch Story-123-c (was 1d738b5).

如果你想保持主,开发和所有远程分支。删除所有不在Github上的本地分支。

$ git fetch --prune

$ git branch | grep -v "origin" | grep -v "develop" | grep -v "master" | xargs git branch -D

1]它将删除远程库中不再使用的远程引用。

2]这将得到你所有分支的列表。从列表中删除包含master、develop或origin(远程分支)的分支。删除列表中的所有分支。

警告-这删除自己的本地分支以及。所以,当你合并了你的分支,并在合并后进行清理时,删除。

我在github上关于这个问题的评论中找到了一个更好的方法:

git branch --merged master --no-color | grep -v "master\|stable\|main" | xargs git branch -d

编辑:添加无颜色选项和排除稳定分支(根据您的情况添加其他分支)

下面是适用于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()
}