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

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

git branch -D[分支名称]也用于本地删除,但会强制删除

其他回答

对于powershell,这将工作:

git branch --format '%(refname:lstrip=2)' --merged `
    | Where-Object { $_ -ne 'master' } `
    | ForEach-Object { git branch -d $_ }
git branch | grep release-1.4 | xargs -n 1 -I % sh -c 'git branch -D %'

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

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

// hard delete

git branch -D $(git branch)

下面的脚本删除分支。使用和修改的风险由你自己承担,等等。

根据这个问题中的其他答案,我最终为自己编写了一个快速bash脚本。我称它为“gitbd”(git branch -D),但如果你使用它,你可以将它重命名为任何你想要的。

gitbd() {
if [ $# -le 1 ]
  then
    local branches_to_delete=`git for-each-ref --format '%(refname:short)' refs/heads/ | grep "$1"`
    printf "Matching branches:\n\n$branches_to_delete\n\nDelete? [Y/n] "
    read -n 1 -r # Immediately continue after getting 1 keypress
    echo # Move to a new line
    if [[ ! $REPLY == 'N' && ! $REPLY == 'n' ]]
      then
        echo $branches_to_delete | xargs git branch -D
    fi
else
  echo "This command takes one arg (match pattern) or no args (match all)"
fi
}

它将提供删除任何匹配模式参数的分支(如果传入),或者在不带参数的情况下调用所有本地分支。它还会给你一个确认步骤,因为我们在删除东西,这很好。

这有点愚蠢——如果没有与模式匹配的分支,它就不会意识到这一点。

一个示例输出运行:

$ gitbd test
Matching branches:

dummy+test1
dummy+test2
dummy+test3

Delete? [Y/n] 

如果你不需要使用Git本身,你也可以手动或编程地删除. Git /refs/heads下的头。以下应该在Bash下进行最小的调整:

shopt -s extglob
rm -rf .git/refs/heads/!(master)

这将删除除主分支外的所有本地分支。由于上游分支存储在.git/refs/remotes下,因此它们将保持不变。

如果你不使用Bash,或者想一次递归很多Git存储库,你可以用GNU find做类似的事情:

find . \
    -path remotes -path logs -prune -o \
    -wholename \*.git/refs/heads/\* \! -name master -print0 |
xargs -0 rm -rf

find解决方案可能更容易移植,但是删除路径和文件名比较棘手,而且可能更容易出错。