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


当前回答

只是将Adam的答案稍微扩展一点:

通过运行Git-config-e--global将其添加到Git配置中

[alias]
    cleanup = "!git branch --merged | grep  -v '\\*\\|master\\|develop' | xargs -n 1 -r git branch -d"

然后,您可以通过简单的git清理来删除所有本地合并分支。

其他回答

基于这些答案,我也制作了自己的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
}

我使用git流式命名方案,因此这对我来说非常安全:

git branch --merged | grep -e "^\s\+\(fix\|feature\)/" | xargs git branch -d

它主要查找以字符串fix/或feature/开头的合并提交。

在安装了gitbash的Windows上,egrep-v将无法工作

git branch --merged | grep -E -v "(master|test|dev)" | xargs git branch -d

其中grep-E-v等于egrep-v

使用-d删除已合并的分支或-D删除未合并的分支

我使用以下Ruby脚本删除已经合并的本地和远程分支。如果我对一个有多个遥控器的存储库执行此操作,并且只想从一个遥控器中删除,那么我只需在遥控器列表中添加一个select语句,即可获得所需的遥控器。

#!/usr/bin/env ruby

current_branch = `git symbolic-ref --short HEAD`.chomp
if current_branch != "master"
  if $?.exitstatus == 0
    puts "WARNING: You are on branch #{current_branch}, NOT master."
  else
    puts "WARNING: You are not on a branch"
  end
  puts
end

puts "Fetching merged branches..."
remote_branches= `git branch -r --merged`.
  split("\n").
  map(&:strip).
  reject {|b| b =~ /\/(#{current_branch}|master)/}

local_branches= `git branch --merged`.
  gsub(/^\* /, '').
  split("\n").
  map(&:strip).
  reject {|b| b =~ /(#{current_branch}|master)/}

if remote_branches.empty? && local_branches.empty?
  puts "No existing branches have been merged into #{current_branch}."
else
  puts "This will remove the following branches:"
  puts remote_branches.join("\n")
  puts local_branches.join("\n")
  puts "Proceed?"
  if gets =~ /^y/i
    remote_branches.each do |b|
      remote, branch = b.split(/\//)
      `git push #{remote} :#{branch}`
    end

    # Remove local branches
    `git branch -d #{local_branches.join(' ')}`
  else
    puts "No branches removed."
  end
end

git从git额外回购中删除合并的分支。

https://github.com/tj/git-extras/blob/master/Commands.md#git-删除合并的分支