如何删除已合并的所有Git分支?

时间:2022-09-19 15:09:08

I have many Git branches. How do I delete branches which have already been merged? Is there an easy way to delete them all instead of deleting them one by one?

我有很多Git分支。如何删除已经合并的分支?有没有一种简单的方法来删除它们,而不是逐个删除它们?

31 个解决方案

#1


2099  

UPDATE:

更新:

You can add other branches to exclude like master and dev if your workflow has those as a possible ancestor. Usually I branch off of a "sprint-start" tag and master, dev and qa are not ancestors.

如果您的工作流有可能的祖先,您可以添加其他分支来排除像master和dev这样的分支。通常我从一个“sprintstart”标签和master、dev和qa分支中分支,而不是祖先。

To delete all local branches that are already merged into the currently checked out branch:

删除已合并到当前检出分支的所有本地分支:

git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d

You can see that master and dev are excluded in case they are an ancestor.

你可以看到,master和dev被排除在外,以防它们是祖先。


You can delete a merged local branch with:

您可以删除合并的本地分支:

git branch -d branchname

If it's not merged, use:

如果未合并,请使用:

git branch -D branchname

To delete it from the remote in old versions of Git use:

从旧版本的Git中删除它:

git push origin :branchname

In more recent versions of Git use:

在最近的Git版本中:

git push --delete origin branchname

Once you delete the branch from the remote, you can prune to get rid of remote tracking branches with:

一旦您从远程删除了分支,您可以删除远程跟踪分支:

git remote prune origin

or prune individual remote tracking branches, as the other answer suggests, with:

另一个答案是:修剪单个的远程跟踪分支。

git branch -dr branchname

Hope this helps.

希望这个有帮助。

#2


296  

To delete all branches on remote that are already merged:

删除已合并的远程的所有分支:

git branch -r --merged | grep -v master | sed 's/origin\//:/' | xargs -n 1 git push origin

In more recent versions of Git

在最新版本的Git中。

git branch -r --merged | grep -v master | sed 's/origin\///' | xargs -n 1 git push --delete origin

#3


124  

Just extending Adam's answer a little bit:

只是把亚当的答案扩展了一下:

Add this to your Git configuration by running git config -e --global

通过运行Git config -e——全局变量,将其添加到Git配置中。

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

And then you can delete all the local merged branches doing a simple git cleanup.

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

#4


72  

This also works to delete all merged branches except master.

这也可以删除除master之外的所有合并分支。

git branch --merged | grep -v '^* master$' | grep -v '^  master$' | xargs git branch -d

#5


54  

You'll want to exclude the master & develop branches from those commands.

您将希望排除master &从这些命令中开发分支。

Local git clear:

本地git清楚:

git branch --merged | grep -v '\*\|master\|develop' | xargs -n 1 git branch -d

Remote git clear:

远程git清楚:

git branch -r --merged | grep -v '\*\|master\|develop' | sed 's/origin\///' | xargs -n 1 git push --delete origin

Sync local registry of remote branches:

同步本地的远程分支注册表:

git fetch -p

#6


27  

For those of you that are on Windows and prefer PowerShell scripts, here is one that deletes local merged branches:

对于那些在Windows上和喜欢PowerShell脚本的人来说,这里有一个删除本地合并分支的方法:

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

#7


18  

Git Sweep does a great job of this.

Git扫描在这方面做得很好。

#8


12  

You can add the commit to the --merged option. This way you can make sure only to remove branches which are merged into i.e. the origin/master

您可以将commit添加到-merge选项。这样,您可以确保只删除合并到的分支,即源/主。

Following command will remove merged branches from your origin.

下面的命令将从您的原点删除合并的分支。

git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 git push origin --delete 

You can test which branches will be removed replacing the git push origin --delete with echo

您可以测试哪些分支将被删除,以替换git推送源——用echo删除。

git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 echo

#9


11  

I use the following Ruby script to delete my already merged local and remote branches. If I'm doing it for a repository with multiple remotes and only want to delete from one, I just add a select statement to the remotes list to only get the remotes I want.

我使用下面的Ruby脚本删除已经合并的本地和远程分支。如果我为一个具有多个remotes的存储库执行它,并且只希望从其中删除一个,那么我只是在remotes列表中添加一个select语句,以得到我想要的remotes。

#!/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

#10


11  

Using Git version 2.5.0:

使用Git版本2.5.0:

git branch -d `git branch --merged`

#11


8  

kuboon's answer missed deleting branches which have the word master in the branch name. The following improves on his answer:

kuboon的答案没有删除分支名称中有“master”的分支。以下是他的回答:

git branch -r --merged | grep -v "origin/master$" | sed 's/\s*origin\///' | xargs -n 1 git push --delete origin

Of course, it does not delete the "master" branch itself :)

当然,它不会删除“master”分支本身:)

#12


8  

How to delete merged branches in PowerShell console

git branch --merged | %{git branch -d $_.Trim()}

See GitHub for Windows

看到GitHub的窗户

#13


7  

There is no command in Git that will do this for you automatically. But you can write a script that uses Git commands to give you what you need. This could be done in many ways depending on what branching model you are using.

Git中没有命令可以自动完成这个任务。但是您可以编写一个脚本,使用Git命令来满足您的需要。这可以通过多种方式实现,这取决于您使用的分支模型。

If you need to know if a branch has been merged into master the following command will yield no output if myTopicBranch has been merged (i.e. you can delete it)

如果您需要知道一个分支是否已被合并到master中,如果myTopicBranch被合并(即您可以删除它),那么以下命令将不会产生输出

$ git rev-list master | grep $(git rev-parse myTopicBranch)

You could use the Git branch command and parse out all branches in Bash and do a for loop over all branches. In this loop you check with above command if you can delete the branch or not.

您可以使用Git分支命令来解析Bash中的所有分支,并对所有分支执行for循环。在这个循环中,如果您可以删除分支,您可以使用上面的命令进行检查。

#14


6  

git branch --merged | grep -Ev '^(. master|\*)' | xargs -n 1 git branch -d will delete all local branches except the current checked out branch and/or master.

git分支——| grep ev ' ^(合并。|\*)' | xargs - n1git分支-d将删除除当前签出的分支和/或master之外的所有本地分支。

Here's a helpful article for those looking to understand these commands: Git Clean: Delete Already Merged Branches, by Steven Harman.

这里有一篇很有用的文章,可以帮助那些想了解这些命令的人:Git Clean:删除已经合并的分支,由Steven Harman。

#15


5  

You can use git-del-br tool.

您可以使用git-del-br工具。

git-del-br -a

You can install it via pip using

您可以使用pip安装它。

pip install git-del-br

P.S: I am the author of the tool. Any suggestions/feedback are welcome.

P。S:我是这个工具的作者。任何建议/反馈是受欢迎的。

#16


5  

Alias version of Adam's updated answer:

亚当更新后的答案的别名:

[alias]
    branch-cleanup = "!git branch --merged | egrep -v \"(^\\*|master|dev)\" | xargs git branch -d #"

Also, see this answer for handy tips on escaping complex aliases.

此外,请参阅此答案,以了解如何避免复杂的别名。

#17


4  

If you'd like to delete all local branches that are already merged in to the branch that you are currently on, then I've come up with a safe command to do so, based on earlier answers:

如果您想要删除已经合并到您当前所在的分支的所有本地分支,那么我已经提出了一个安全的命令,基于更早的答案:

git branch --merged | grep -v \* | grep -v '^\s*master$' | xargs -t -n 1 git branch -d

This command will not affect your current branch or your master branch. It will also tell you what it's doing before it does it, using the -t flag of xargs.

这个命令不会影响您当前的分支或您的主分支。它还会告诉你它在做什么之前,使用xargs的-t标志。

#18


4  

Try the following command:

试试下面的命令:

git branch -d $(git branch --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))

git分支-d $(git分支—合并| grep -vw $(git rev-parse—abbrev-ref HEAD))

By using git rev-parse will get the current branch name in order to exclude it. If you got the error, that means there are no local branches to remove.

通过使用git rev-parse将获得当前的分支名称,以排除它。如果您有错误,这意味着没有本地分支可以删除。

To do the same with remote branches (change origin with your remote name), try:

要对远程分支执行相同的操作(以您的远程名称更改原点),请尝试:

git push origin -vd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD) | cut -d/ -f2)

git推源-vd $(git分支-r -合并| grep -vw $(git rev-parse—abbrev-ref HEAD) | cut -d/ -f2)

In case you've multiple remotes, add grep origin | before cut to filter only the origin.

如果你有多个遥控器,在切割之前添加grep原点|,只过滤原点。

If above command fails, try to delete the merged remote-tracking branches first:

如果上面的命令失败,试着先删除合并的远程跟踪分支:

git branch -rd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))

git分支-rd $(git分支-r—合并| grep -vw $(git rev-parse—abbrev-ref HEAD))

Then git fetch the remote again and use the previous git push -vdcommand again.

然后git再次取回远程,并再次使用前面的git push -vdcommand。

If you're using it often, consider adding as aliases into your ~/.gitconfig file.

如果你经常使用它,可以考虑在你的~/中添加别名。gitconfig文件。

In case you've removed some branches by mistake, use git reflog to find the lost commits.

如果您错误地删除了一些分支,请使用git reflog来查找丢失的提交。

#19


4  

Based on some of these answers I made my own Bash script to do it too!

基于这些答案,我也编写了自己的Bash脚本!

It uses git branch --merged and git branch -d to delete the branches that have been merged and prompts you for each of the branches before deleting.

它使用git分支—合并和git分支-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
}

#20


4  

I use a git-flow esque naming scheme, so this works very safely for me:

我使用了一个git-flow风格的命名方案,所以这对我来说非常安全:

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

It basically looks for merged commits that start with either string fix/ or feature/.

它主要寻找合并的提交,从字符串修复/或功能/特性开始。

#21


3  

Write a script in which Git checks out all the branches that have been merged to master.

编写一个脚本,其中Git检查所有已合并到主的分支。

Then do git checkout master.

然后是git签出器。

Finally, delete the merged branches.

最后,删除合并的分支。

for k in $(git branch -ra --merged | egrep -v "(^\*|master)"); do
  branchnew=$(echo $k | sed -e "s/origin\///" | sed -e "s/remotes\///")
  echo branch-name: $branchnew
  git checkout $branchnew
done

git checkout master

for k in $(git branch -ra --merged | egrep -v "(^\*|master)"); do
  branchnew=$(echo $k | sed -e "s/origin\///" | sed -e "s/remotes\///")
  echo branch-name: $branchnew
  git push origin --delete $branchnew
done

#22


3  

Below query works for me

下面的查询对我有用。

for branch in  `git branch -r --merged | grep -v '\*\|master\|develop'|awk 'NR > 0 {print$1}'|awk '{gsub(/origin\//, "")}1'`;do git push origin --delete $branch; done

and this will filter any given branch in the grep pipe.

这将过滤grep管道中的任何分支。

Works well over http clone, but not so well for the ssh connection.

在http克隆上工作得很好,但对ssh连接却不太好。

#23


1  

To avoid accidentally running the command from any other branch than master I use the following bash script. Otherwise, running git branch --merged | grep -v "\*" | xargs -n 1 git branch -d from a branch that has been merged of off master could delete the master branch.

为了避免意外地从任何其他分支运行命令,我使用了下面的bash脚本。否则,运行git分支——合并| grep -v“\*”| xargs - n1git分支-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

#24


0  

To delete local branches that have been merged to master branch I'm using the following alias (git config -e --global):

要删除已合并到主分支的本地分支,我使用以下别名(git config -e—global):

cleanup = "!git branch --merged master | grep -v '^*\\|master' | xargs -n 1 git branch -D"

I'm using git branch -D to avoid error: The branch 'some-branch' is not fully merged. messages while my current checkout is different from master branch.

我使用git分支-D来避免错误:分支“some-branch”并没有完全合并。在我当前签出时,消息与主分支不同。

#25


0  

Windoze-friendly Python script (because git-sweep choked on Wesnoth repository):

友好的Python脚本(因为它在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

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

#26


0  

If you are using branching model like HubFlow or GitFlow you can use this command to remove the merged feature branches:

如果您使用的是分支模型,如HubFlow或GitFlow,您可以使用此命令来删除合并的特性分支:

git branch --merged | grep feature.* | grep -v "\*" | xargs -n 1 git branch -d

git分支——合并| grep特性。* | grep -v "\*" | xargs - n1git分支-d。

#27


0  

If you wish to delete local branches that have been merged as well as delete their remotes here's the one-liner I prefer:

如果您希望删除已合并的本地分支,并删除它们的remotes,那么我更愿意使用:

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

#28


0  

for b in $(git branch -a | grep -v "\(master\|remotes\)"); do \ 
git branch -D $b; done && git fetch -p

#29


0  

Let's say I have a remote named upstream and an origin (GitHub style, my fork is origin, upstream is upstream).

假设我有一个远程命名的上游和一个原点(GitHub风格,我的fork是起源,上游是上游)。

I don't want to delete ANY masters, HEAD, or anything from the upstream. I also don't want to delete the develop branch as that is our common branch we create PRs from.

我不想从上游删除任何主人、头或任何东西。我也不想删除开发分支,因为这是我们创建PRs的公共分支。

List all remote branches, filtered by ones that were merged:

列出所有被合并的远程分支:

git branch -r

Remove lines from that list that contain words I know are in branch names I don't want to remove:

从列表中删除包含我知道的单词的行,它们在分支名称中,我不想删除:

sed '/develop\|master\|HEAD\|upstream/d'

Remove the remote name from the reference name (origin/somebranch becomes somebranch):

从引用名称中删除远程名称(origin/somebranch成为somebranch):

sed 's/.*\///'

Use xargs to call a one-liner:

使用xargs来调用一行程序:

xargs git push --delete origin

Pipe it all together you get:

把它连接在一起:

git branch -r --merged | sed '/develop\|master\|HEAD\|upstream/d' |  sed 's/.*\///' | xargs git push --delete origin

This will leave me with only some branches that I have worked on, but have not merged. You can then remove them one by one as there shouldn't be too many.

这将留给我一些我曾经工作过的分支,但是没有合并。你可以逐个移除它们,因为不应该有太多。

Find branches you no longer want:

找到你不再需要的分支:

git branch -ar

Say you find branch1, branch2, and branch3 you want to delete:

说你找到了branch1, branch2和branch3你想要删除:

git push --delete origin branch1 branch2 branch3

#30


0  

My Bash script contribution is based loosely on mmrobin's answer.

我的Bash脚本贡献基于mmrobin的答案。

It takes some useful parameters specifying includes and excludes, or to examine/remove only local or remote branches instead of both.

它需要一些有用的参数来指定包含和排除,或者只检查/删除本地或远程分支,而不是两者。

#!/bin/bash

# exclude branches regex, configure as "(branch1|branch2|etc)$"
excludes_default="(master|next|ag/doc-updates)$"
excludes="__NOTHING__"
includes=
merged="--merged"
local=1
remote=1

while [ $# -gt 0 ]; do
  case "$1" in
  -i) shift; includes="$includes $1" ;;
  -e) shift; excludes="$1" ;;
  --no-local) local=0 ;;
  --no-remote) remote=0 ;;
  --all) merged= ;;
  *) echo "Unknown argument $1"; exit 1 ;;
  esac
  shift   # next option
done

if [ "$includes" == "" ]; then
  includes=".*"
else
  includes="($(echo $includes | sed -e 's/ /|/g'))"
fi

current_branch=$(git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
if [ "$current_branch" != "master" ]; then
  echo "WARNING: You are on branch $current_branch, NOT master."
fi
echo -e "Fetching branches...\n"

git remote update --prune
remote_branches=$(git branch -r $merged | grep -v "/$current_branch$" | grep -v -E "$excludes" | grep -v -E "$excludes_default" | grep -E "$includes")
local_branches=$(git branch $merged | grep -v "$current_branch$" | grep -v -E "$excludes" | grep -v -E "$excludes_default" | grep -E "$includes")
if [ -z "$remote_branches" ] && [ -z "$local_branches" ]; then
  echo "No existing branches have been merged into $current_branch."
else
  echo "This will remove the following branches:"
  if [ "$remote" == 1 -a -n "$remote_branches" ]; then
    echo "$remote_branches"
  fi
  if [ "$local" == 1 -a -n "$local_branches" ]; then
    echo "$local_branches"
  fi
  read -p "Continue? (y/n): " -n 1 choice
  echo
  if [ "$choice" == "y" ] || [ "$choice" == "Y" ]; then
    if [ "$remote" == 1 ]; then
      remotes=$(git remote)
      # Remove remote branches
      for remote in $remotes
      do
        branches=$(echo "$remote_branches" | grep "$remote/" | sed "s/$remote\/\(.*\)/:\1 /g" | tr -d '\n')
        git push $remote $branches
      done
    fi

    if [ "$local" == 1 ]; then
      # Remove local branches
      locals=$(echo "$local_branches" | sed 's/origin\///g' | tr -d '\n')
      if [ -z "$locals" ]; then
        echo "No branches removed."
      else
        git branch -d $(echo "$locals" | tr -d '\n')
      fi
    fi
  fi
fi

#1


2099  

UPDATE:

更新:

You can add other branches to exclude like master and dev if your workflow has those as a possible ancestor. Usually I branch off of a "sprint-start" tag and master, dev and qa are not ancestors.

如果您的工作流有可能的祖先,您可以添加其他分支来排除像master和dev这样的分支。通常我从一个“sprintstart”标签和master、dev和qa分支中分支,而不是祖先。

To delete all local branches that are already merged into the currently checked out branch:

删除已合并到当前检出分支的所有本地分支:

git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d

You can see that master and dev are excluded in case they are an ancestor.

你可以看到,master和dev被排除在外,以防它们是祖先。


You can delete a merged local branch with:

您可以删除合并的本地分支:

git branch -d branchname

If it's not merged, use:

如果未合并,请使用:

git branch -D branchname

To delete it from the remote in old versions of Git use:

从旧版本的Git中删除它:

git push origin :branchname

In more recent versions of Git use:

在最近的Git版本中:

git push --delete origin branchname

Once you delete the branch from the remote, you can prune to get rid of remote tracking branches with:

一旦您从远程删除了分支,您可以删除远程跟踪分支:

git remote prune origin

or prune individual remote tracking branches, as the other answer suggests, with:

另一个答案是:修剪单个的远程跟踪分支。

git branch -dr branchname

Hope this helps.

希望这个有帮助。

#2


296  

To delete all branches on remote that are already merged:

删除已合并的远程的所有分支:

git branch -r --merged | grep -v master | sed 's/origin\//:/' | xargs -n 1 git push origin

In more recent versions of Git

在最新版本的Git中。

git branch -r --merged | grep -v master | sed 's/origin\///' | xargs -n 1 git push --delete origin

#3


124  

Just extending Adam's answer a little bit:

只是把亚当的答案扩展了一下:

Add this to your Git configuration by running git config -e --global

通过运行Git config -e——全局变量,将其添加到Git配置中。

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

And then you can delete all the local merged branches doing a simple git cleanup.

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

#4


72  

This also works to delete all merged branches except master.

这也可以删除除master之外的所有合并分支。

git branch --merged | grep -v '^* master$' | grep -v '^  master$' | xargs git branch -d

#5


54  

You'll want to exclude the master & develop branches from those commands.

您将希望排除master &从这些命令中开发分支。

Local git clear:

本地git清楚:

git branch --merged | grep -v '\*\|master\|develop' | xargs -n 1 git branch -d

Remote git clear:

远程git清楚:

git branch -r --merged | grep -v '\*\|master\|develop' | sed 's/origin\///' | xargs -n 1 git push --delete origin

Sync local registry of remote branches:

同步本地的远程分支注册表:

git fetch -p

#6


27  

For those of you that are on Windows and prefer PowerShell scripts, here is one that deletes local merged branches:

对于那些在Windows上和喜欢PowerShell脚本的人来说,这里有一个删除本地合并分支的方法:

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

#7


18  

Git Sweep does a great job of this.

Git扫描在这方面做得很好。

#8


12  

You can add the commit to the --merged option. This way you can make sure only to remove branches which are merged into i.e. the origin/master

您可以将commit添加到-merge选项。这样,您可以确保只删除合并到的分支,即源/主。

Following command will remove merged branches from your origin.

下面的命令将从您的原点删除合并的分支。

git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 git push origin --delete 

You can test which branches will be removed replacing the git push origin --delete with echo

您可以测试哪些分支将被删除,以替换git推送源——用echo删除。

git branch -r --merged origin/master | grep -v "^.*master" | sed s:origin/:: |xargs -n 1 echo

#9


11  

I use the following Ruby script to delete my already merged local and remote branches. If I'm doing it for a repository with multiple remotes and only want to delete from one, I just add a select statement to the remotes list to only get the remotes I want.

我使用下面的Ruby脚本删除已经合并的本地和远程分支。如果我为一个具有多个remotes的存储库执行它,并且只希望从其中删除一个,那么我只是在remotes列表中添加一个select语句,以得到我想要的remotes。

#!/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

#10


11  

Using Git version 2.5.0:

使用Git版本2.5.0:

git branch -d `git branch --merged`

#11


8  

kuboon's answer missed deleting branches which have the word master in the branch name. The following improves on his answer:

kuboon的答案没有删除分支名称中有“master”的分支。以下是他的回答:

git branch -r --merged | grep -v "origin/master$" | sed 's/\s*origin\///' | xargs -n 1 git push --delete origin

Of course, it does not delete the "master" branch itself :)

当然,它不会删除“master”分支本身:)

#12


8  

How to delete merged branches in PowerShell console

git branch --merged | %{git branch -d $_.Trim()}

See GitHub for Windows

看到GitHub的窗户

#13


7  

There is no command in Git that will do this for you automatically. But you can write a script that uses Git commands to give you what you need. This could be done in many ways depending on what branching model you are using.

Git中没有命令可以自动完成这个任务。但是您可以编写一个脚本,使用Git命令来满足您的需要。这可以通过多种方式实现,这取决于您使用的分支模型。

If you need to know if a branch has been merged into master the following command will yield no output if myTopicBranch has been merged (i.e. you can delete it)

如果您需要知道一个分支是否已被合并到master中,如果myTopicBranch被合并(即您可以删除它),那么以下命令将不会产生输出

$ git rev-list master | grep $(git rev-parse myTopicBranch)

You could use the Git branch command and parse out all branches in Bash and do a for loop over all branches. In this loop you check with above command if you can delete the branch or not.

您可以使用Git分支命令来解析Bash中的所有分支,并对所有分支执行for循环。在这个循环中,如果您可以删除分支,您可以使用上面的命令进行检查。

#14


6  

git branch --merged | grep -Ev '^(. master|\*)' | xargs -n 1 git branch -d will delete all local branches except the current checked out branch and/or master.

git分支——| grep ev ' ^(合并。|\*)' | xargs - n1git分支-d将删除除当前签出的分支和/或master之外的所有本地分支。

Here's a helpful article for those looking to understand these commands: Git Clean: Delete Already Merged Branches, by Steven Harman.

这里有一篇很有用的文章,可以帮助那些想了解这些命令的人:Git Clean:删除已经合并的分支,由Steven Harman。

#15


5  

You can use git-del-br tool.

您可以使用git-del-br工具。

git-del-br -a

You can install it via pip using

您可以使用pip安装它。

pip install git-del-br

P.S: I am the author of the tool. Any suggestions/feedback are welcome.

P。S:我是这个工具的作者。任何建议/反馈是受欢迎的。

#16


5  

Alias version of Adam's updated answer:

亚当更新后的答案的别名:

[alias]
    branch-cleanup = "!git branch --merged | egrep -v \"(^\\*|master|dev)\" | xargs git branch -d #"

Also, see this answer for handy tips on escaping complex aliases.

此外,请参阅此答案,以了解如何避免复杂的别名。

#17


4  

If you'd like to delete all local branches that are already merged in to the branch that you are currently on, then I've come up with a safe command to do so, based on earlier answers:

如果您想要删除已经合并到您当前所在的分支的所有本地分支,那么我已经提出了一个安全的命令,基于更早的答案:

git branch --merged | grep -v \* | grep -v '^\s*master$' | xargs -t -n 1 git branch -d

This command will not affect your current branch or your master branch. It will also tell you what it's doing before it does it, using the -t flag of xargs.

这个命令不会影响您当前的分支或您的主分支。它还会告诉你它在做什么之前,使用xargs的-t标志。

#18


4  

Try the following command:

试试下面的命令:

git branch -d $(git branch --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))

git分支-d $(git分支—合并| grep -vw $(git rev-parse—abbrev-ref HEAD))

By using git rev-parse will get the current branch name in order to exclude it. If you got the error, that means there are no local branches to remove.

通过使用git rev-parse将获得当前的分支名称,以排除它。如果您有错误,这意味着没有本地分支可以删除。

To do the same with remote branches (change origin with your remote name), try:

要对远程分支执行相同的操作(以您的远程名称更改原点),请尝试:

git push origin -vd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD) | cut -d/ -f2)

git推源-vd $(git分支-r -合并| grep -vw $(git rev-parse—abbrev-ref HEAD) | cut -d/ -f2)

In case you've multiple remotes, add grep origin | before cut to filter only the origin.

如果你有多个遥控器,在切割之前添加grep原点|,只过滤原点。

If above command fails, try to delete the merged remote-tracking branches first:

如果上面的命令失败,试着先删除合并的远程跟踪分支:

git branch -rd $(git branch -r --merged | grep -vw $(git rev-parse --abbrev-ref HEAD))

git分支-rd $(git分支-r—合并| grep -vw $(git rev-parse—abbrev-ref HEAD))

Then git fetch the remote again and use the previous git push -vdcommand again.

然后git再次取回远程,并再次使用前面的git push -vdcommand。

If you're using it often, consider adding as aliases into your ~/.gitconfig file.

如果你经常使用它,可以考虑在你的~/中添加别名。gitconfig文件。

In case you've removed some branches by mistake, use git reflog to find the lost commits.

如果您错误地删除了一些分支,请使用git reflog来查找丢失的提交。

#19


4  

Based on some of these answers I made my own Bash script to do it too!

基于这些答案,我也编写了自己的Bash脚本!

It uses git branch --merged and git branch -d to delete the branches that have been merged and prompts you for each of the branches before deleting.

它使用git分支—合并和git分支-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
}

#20


4  

I use a git-flow esque naming scheme, so this works very safely for me:

我使用了一个git-flow风格的命名方案,所以这对我来说非常安全:

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

It basically looks for merged commits that start with either string fix/ or feature/.

它主要寻找合并的提交,从字符串修复/或功能/特性开始。

#21


3  

Write a script in which Git checks out all the branches that have been merged to master.

编写一个脚本,其中Git检查所有已合并到主的分支。

Then do git checkout master.

然后是git签出器。

Finally, delete the merged branches.

最后,删除合并的分支。

for k in $(git branch -ra --merged | egrep -v "(^\*|master)"); do
  branchnew=$(echo $k | sed -e "s/origin\///" | sed -e "s/remotes\///")
  echo branch-name: $branchnew
  git checkout $branchnew
done

git checkout master

for k in $(git branch -ra --merged | egrep -v "(^\*|master)"); do
  branchnew=$(echo $k | sed -e "s/origin\///" | sed -e "s/remotes\///")
  echo branch-name: $branchnew
  git push origin --delete $branchnew
done

#22


3  

Below query works for me

下面的查询对我有用。

for branch in  `git branch -r --merged | grep -v '\*\|master\|develop'|awk 'NR > 0 {print$1}'|awk '{gsub(/origin\//, "")}1'`;do git push origin --delete $branch; done

and this will filter any given branch in the grep pipe.

这将过滤grep管道中的任何分支。

Works well over http clone, but not so well for the ssh connection.

在http克隆上工作得很好,但对ssh连接却不太好。

#23


1  

To avoid accidentally running the command from any other branch than master I use the following bash script. Otherwise, running git branch --merged | grep -v "\*" | xargs -n 1 git branch -d from a branch that has been merged of off master could delete the master branch.

为了避免意外地从任何其他分支运行命令,我使用了下面的bash脚本。否则,运行git分支——合并| grep -v“\*”| xargs - n1git分支-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

#24


0  

To delete local branches that have been merged to master branch I'm using the following alias (git config -e --global):

要删除已合并到主分支的本地分支,我使用以下别名(git config -e—global):

cleanup = "!git branch --merged master | grep -v '^*\\|master' | xargs -n 1 git branch -D"

I'm using git branch -D to avoid error: The branch 'some-branch' is not fully merged. messages while my current checkout is different from master branch.

我使用git分支-D来避免错误:分支“some-branch”并没有完全合并。在我当前签出时,消息与主分支不同。

#25


0  

Windoze-friendly Python script (because git-sweep choked on Wesnoth repository):

友好的Python脚本(因为它在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

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

#26


0  

If you are using branching model like HubFlow or GitFlow you can use this command to remove the merged feature branches:

如果您使用的是分支模型,如HubFlow或GitFlow,您可以使用此命令来删除合并的特性分支:

git branch --merged | grep feature.* | grep -v "\*" | xargs -n 1 git branch -d

git分支——合并| grep特性。* | grep -v "\*" | xargs - n1git分支-d。

#27


0  

If you wish to delete local branches that have been merged as well as delete their remotes here's the one-liner I prefer:

如果您希望删除已合并的本地分支,并删除它们的remotes,那么我更愿意使用:

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

#28


0  

for b in $(git branch -a | grep -v "\(master\|remotes\)"); do \ 
git branch -D $b; done && git fetch -p

#29


0  

Let's say I have a remote named upstream and an origin (GitHub style, my fork is origin, upstream is upstream).

假设我有一个远程命名的上游和一个原点(GitHub风格,我的fork是起源,上游是上游)。

I don't want to delete ANY masters, HEAD, or anything from the upstream. I also don't want to delete the develop branch as that is our common branch we create PRs from.

我不想从上游删除任何主人、头或任何东西。我也不想删除开发分支,因为这是我们创建PRs的公共分支。

List all remote branches, filtered by ones that were merged:

列出所有被合并的远程分支:

git branch -r

Remove lines from that list that contain words I know are in branch names I don't want to remove:

从列表中删除包含我知道的单词的行,它们在分支名称中,我不想删除:

sed '/develop\|master\|HEAD\|upstream/d'

Remove the remote name from the reference name (origin/somebranch becomes somebranch):

从引用名称中删除远程名称(origin/somebranch成为somebranch):

sed 's/.*\///'

Use xargs to call a one-liner:

使用xargs来调用一行程序:

xargs git push --delete origin

Pipe it all together you get:

把它连接在一起:

git branch -r --merged | sed '/develop\|master\|HEAD\|upstream/d' |  sed 's/.*\///' | xargs git push --delete origin

This will leave me with only some branches that I have worked on, but have not merged. You can then remove them one by one as there shouldn't be too many.

这将留给我一些我曾经工作过的分支,但是没有合并。你可以逐个移除它们,因为不应该有太多。

Find branches you no longer want:

找到你不再需要的分支:

git branch -ar

Say you find branch1, branch2, and branch3 you want to delete:

说你找到了branch1, branch2和branch3你想要删除:

git push --delete origin branch1 branch2 branch3

#30


0  

My Bash script contribution is based loosely on mmrobin's answer.

我的Bash脚本贡献基于mmrobin的答案。

It takes some useful parameters specifying includes and excludes, or to examine/remove only local or remote branches instead of both.

它需要一些有用的参数来指定包含和排除,或者只检查/删除本地或远程分支,而不是两者。

#!/bin/bash

# exclude branches regex, configure as "(branch1|branch2|etc)$"
excludes_default="(master|next|ag/doc-updates)$"
excludes="__NOTHING__"
includes=
merged="--merged"
local=1
remote=1

while [ $# -gt 0 ]; do
  case "$1" in
  -i) shift; includes="$includes $1" ;;
  -e) shift; excludes="$1" ;;
  --no-local) local=0 ;;
  --no-remote) remote=0 ;;
  --all) merged= ;;
  *) echo "Unknown argument $1"; exit 1 ;;
  esac
  shift   # next option
done

if [ "$includes" == "" ]; then
  includes=".*"
else
  includes="($(echo $includes | sed -e 's/ /|/g'))"
fi

current_branch=$(git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
if [ "$current_branch" != "master" ]; then
  echo "WARNING: You are on branch $current_branch, NOT master."
fi
echo -e "Fetching branches...\n"

git remote update --prune
remote_branches=$(git branch -r $merged | grep -v "/$current_branch$" | grep -v -E "$excludes" | grep -v -E "$excludes_default" | grep -E "$includes")
local_branches=$(git branch $merged | grep -v "$current_branch$" | grep -v -E "$excludes" | grep -v -E "$excludes_default" | grep -E "$includes")
if [ -z "$remote_branches" ] && [ -z "$local_branches" ]; then
  echo "No existing branches have been merged into $current_branch."
else
  echo "This will remove the following branches:"
  if [ "$remote" == 1 -a -n "$remote_branches" ]; then
    echo "$remote_branches"
  fi
  if [ "$local" == 1 -a -n "$local_branches" ]; then
    echo "$local_branches"
  fi
  read -p "Continue? (y/n): " -n 1 choice
  echo
  if [ "$choice" == "y" ] || [ "$choice" == "Y" ]; then
    if [ "$remote" == 1 ]; then
      remotes=$(git remote)
      # Remove remote branches
      for remote in $remotes
      do
        branches=$(echo "$remote_branches" | grep "$remote/" | sed "s/$remote\/\(.*\)/:\1 /g" | tr -d '\n')
        git push $remote $branches
      done
    fi

    if [ "$local" == 1 ]; then
      # Remove local branches
      locals=$(echo "$local_branches" | sed 's/origin\///g' | tr -d '\n')
      if [ -z "$locals" ]; then
        echo "No branches removed."
      else
        git branch -d $(echo "$locals" | tr -d '\n')
      fi
    fi
  fi
fi