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

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

当前回答

我写了一个shell脚本,以删除除开发之外的所有本地分支

branches=$(git branch | tr -d " *")
output=""
for branch in $branches 
do
  if [[ $branch != "develop" ]]; then
    output="$output $branch"
  fi
done
git branch -d $output

其他回答

下面是适用于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分支,但保留主

git branch | grep -v "main" | xargs git branch -D 

我没有grep或其他unix在我的盒子上,但这从VSCode的终端工作:

Git branch -d $(Git branch).trim()

我使用小写的d,这样它就不会删除未合并的分支。

当我这样做的时候,我也在master上,所以* master不存在,所以它不会试图删除master。

删除linux中所有本地分支,除了您所在的分支

// hard delete

git branch -D $(git branch)

从Windows命令行删除除当前签出的分支以外的所有分支:

for /f "tokens=*" %f in ('git branch ^| find /v "*"') do git branch -D %f