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

随着时间的推移,由于懒惰或健忘,我最终会得到一个很大的本地分支列表,其中一些(如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 branch -D `git branch | awk '{ if ($0 !~ /<Branch_You_Want_to_Keep>/) printf "%s", $0 }'`

如果您想保留多个分支,那么

git branch -D `git branch | awk '{ if ($0 !~ /<Branch_You_Want_to_Keep1>|<Branch_You_Want_to_Keep2>/) printf "%s", $0 }'`

希望这能帮助到一些人。

其他回答

git branch | grep release-1.4 | xargs -n 1 -I % sh -c 'git branch -D %'

删除所有名称与模式“release-1.4*”匹配的分支的简单方法。我还定期使用它与票据前缀一起删除所有本地工作分支,但不打扰管道分支。

同时删除多个本地分支

# delete all local unmerged branches
git branch --no-merged | egrep -v "(^\*|master|dev)" | xargs git branch -D
# delete all local branches (merged and unmerged).
git branch | egrep -v "(^\*|master|dev)" | xargs git branch -D  

删除远程分支

# Deleting non-existent tracking branches
git remote prune <remote> --dry-run
# Deleting a single remote branch
git push <remote> --delete <branch>
# Deleting many remote branches at once
git branch -r --merged | egrep -v "(^\*|master|dev)" | sed 's/origin\///' | xargs -n 1 git push origin --delete

我写了一个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

我遇到过类似的情况,最近发现下面的命令很有用。

git branch -D `git branch | awk '{ if ($0 !~ /<Branch_You_Want_to_Keep>/) printf "%s", $0 }'`

如果您想保留多个分支,那么

git branch -D `git branch | awk '{ if ($0 !~ /<Branch_You_Want_to_Keep1>|<Branch_You_Want_to_Keep2>/) printf "%s", $0 }'`

希望这能帮助到一些人。

删除所有本地git分支,但保留主

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