How can I delete all Git branches which have been merged?

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?


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.

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.


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 push origin :branchname

In more recent versions of Git use:

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.


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 branch -r --merged | grep -v master | sed 's/origin///' | xargs -n 1 git push --delete origin

Just extending Adam's answer a little bit:

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

[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 .

链接地址: http://www.djcxy.com/p/19490.html

上一篇: 在git中列出每个分支及其最新版本的日期

下一篇: 我如何删除已合并的所有Git分支?