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


当前回答

刚刚为此创建了python脚本:

import sys
from shutil import which
import logging
from subprocess import check_output, call

logger = logging.getLogger(__name__)

if __name__ == '__main__':
    if which("git") is None:
        logger.error("git is not found!")
        sys.exit(-1)

    branches = check_output("git branch -r --merged".split()).strip().decode("utf8").splitlines()
    current = check_output("git branch --show-current".split()).strip().decode("utf8")
    blacklist = ["master", current]

    for b in branches:
        b = b.split("/")[-1]

        if b in blacklist:
            continue
        else:
            if input(f"Do you want to delete branch: '{b}' [y/n]\n").lower() == "y":
                call(f"git branch -D {b}".split())
                call(f"git push --delete origin {b}".split())

其他回答

我使用以下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

为了避免意外地从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

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

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

下面创建一个别名gitcleanup,其中包含一个可选参数分支。默认情况下,它使用远程源的默认分支。已合并到此中的每个分支都将被删除。还有一个-d/-dryrun选项,用于显示将删除的内容。

安装程序

git config --global alias.cleanup '!COMMAND="git branch -D"; while [[ $# -gt 0 ]]; do case "$1" in -d|--dryrun) COMMAND="echo"; shift; ;; *) MAIN_BRANCH="$1"; shift;; esac; done; MAIN_BRANCH="${MAIN_BRANCH:-$(git symbolic-ref refs/remotes/origin/HEAD)}"; git for-each-ref --merged="$MAIN_BRANCH" --no-contains="$MAIN_BRANCH" --format="%(refname:short)" refs/heads/ | xargs -n1 -r $COMMAND;#'

用法:

git cleanup             # delete all branches that have been merged into origin/HEAD
git cleanup master2     # delete all branches that have been merged into master2
git cleanup master2 -d  # do a dryrun (show names of branches that would be delted)

可读代码

谁能读到那句“oneliner”?好了,给你

COMMAND="git branch -D";
while [[ $# -gt 0 ]]; do
  case "$1" in
    -d|--dryrun)
      COMMAND="echo"; 
      shift; 
      ;; 
    *)
      MAIN_BRANCH="$1";
      shift
    ;;
  esac;
done;
MAIN_BRANCH="${MAIN_BRANCH:-$(git symbolic-ref refs/remotes/origin/HEAD)}"; 
git for-each-ref --merged="$MAIN_BRANCH" --no-contains="$MAIN_BRANCH" --format="%(refname:short)" refs/heads/ | xargs -n1 -r $COMMAND;
#

与其他答案有什么不同?

使用--no contains选项过滤掉标识分支(所有其他被删除的分支都已合并到其中的分支),而不是grep-v(如果您特定于分支并指定refs/heads/master,则效果更好)使用远程HEAD检查默认分支名称具有一个参数,用于指定要用作合并主节点的分支具有干式运行选项

对于那些使用Windows并喜欢PowerShell脚本的人,这里有一个删除本地合并分支的脚本:

function Remove-MergedBranches
{
  git branch --merged |
    ForEach-Object { $_.Trim() } |
    Where-Object { $_ -NotMatch "^\*" } |
    Where-Object { -not ( $_ -Like "*master" -or $_ -Like "*main" ) } |
    ForEach-Object { git branch -d $_ }
}

或者简称:

git branch --merged | %{$_.trim()}  | ?{$_ -notmatch 'dev' -and $_ -notmatch 'master' -and $_ -notmatch 'main'} | %{git branch -d $_.trim()}