How do I delete branches which have already been merged? Can I delete them all at once, instead of deleting each branch one-by-one?
NOTE: 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.
First, list locally-tracking branches that were merged in remote (consider using -r
flag to list all remote-tracking branches).
git branch --merged
You might see a few branches you don't want to remove. We can add arguments to skip important branches that we don't want to delete like master or a develop. The following command will skip the master
/main
branch and anything that has 'dev' in it.
git branch --merged | grep -Ev "(^\*|^\+|master|main|dev)"
The first part (^\*|^+
) excludes the current branch and any branch checked out in another worktree.
If you want to skip a branch, you can add it to the grep command as below. The branch skip_branch_name
will not be deleted.
git branch --merged | grep -Ev "(^\*|^\+|master|main|dev|skip_branch_name)"
To delete all local branches that are already merged into the currently checked out branch:
git branch --merged | grep -Ev "(^\*|^\+|master|main|dev)" | xargs --no-run-if-empty 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
To force deletion of an unmerged branch, use:
git branch -D branchname
To delete it from the remote use:
git push --delete origin branchname
git push origin :branchname # for really old git
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