如何删除已合并的分支?我可以一次删除所有分支,而不是逐个删除每个分支吗?


当前回答

Windoze友好的Python脚本(因为git sweep阻塞了Wesnoth存储库):

#!/usr/bin/env python
# Remove merged git branches. Cross-platform way to execute:
#
#   git branch --merged | grep -v master | xargs git branch -d
#
# Requires gitapi - https://bitbucket.org/haard/gitapi
# License: Public Domain

import gitapi

repo = gitapi.Repo('.')
output = repo.git_command('branch', '--merged').strip()
for branch in output.split('\n'):
  branch = branch.strip()
  if branch.strip(' *') != 'master':
    print(repo.git_command('branch', '-d', branch).strip())

https://gist.github.com/techtonik/b3f0d4b9a56dbacb3afc

其他回答

如果您希望删除已合并的本地分支以及删除它们的远程控制器,这里是我更喜欢的一行代码:

git branch --merged | xargs -I_br -- sh -c 'git branch -d _br; git push origin --delete _br'

gitbranch--merged|grep-Ev'^(.master |\*)'|xargs-n 1 gitbranch-d将删除除当前签出的分支和/或主分支外的所有本地分支。

这是一篇有助于理解这些命令的文章:Steven Harman的Git Clean:Delete Already Merged Branches。

基于这些答案,我也制作了自己的Bash脚本来实现这一点!

它使用gitbranch--merged和gitbranch-d删除已合并的分支,并在删除之前提示您输入每个分支。

merged_branches () {
    local current_branch=$(git rev-parse --abbrev-ref HEAD)
    for branch in $(git branch --merged | cut -c3-)
      do
        echo "Branch $branch is already merged into $current_branch."
        echo "Would you like to delete it? [Y]es/[N]o "
        read REPLY
        if [[ $REPLY =~ ^[Yy] ]]; then
            git branch -d $branch
        fi
    done
}

要删除合并的分支,gitdelete合并的分支比shell黑客更健壮、更方便。它还检测重基合并和挤压合并。它的自述文件有更多细节。

为了避免意外地从master以外的任何其他分支运行命令,我使用以下bash脚本。否则,从已合并非主分支的分支运行git branch--merged |grep-v“\*”|xargs-n 1 git branch-d可能会删除主分支。

#!/bin/bash

branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
branch_name="(unnamed branch)"     # detached HEAD
branch_name=${branch_name##refs/heads/}

if [[ $branch_name == 'master' ]]; then
   read -r -p "Are you sure? [y/N] " response
   if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then
       git branch --merged | grep -v "\*" | xargs -n 1 git branch -d
   fi
else
   echo "Refusing to delete branches that are not merged into '$branch_name'. Checkout master first."
fi