Nyambaa Nyambaa - 3 months ago 14
Git Question

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?

Answer

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.