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?
Note: I am not happy with previous answers, (not working on all systems, not working on remote, not specifying the --merged branch, not filtering exactly). So, I add my own answer.
There are two main cases:
Local
You want to delete local branches that are already merged to another local branch. During the deletion, you want to keep some important branches, like master, develop, etc.
git branch --format "%(refname:short)" --merged master | grep -E -v '^master$|^feature/develop$' | xargs -n 1 git branch -d
Notes:
git branch output --format ".." is to strip whitespaces and allow exact grep matchinggrep -E is used instead of egrep, so it works also in systems without egrep (i.e.: git for windows).grep -E -v '^master$|^feature/develop$' is to specify local branches that I don't want to deletexargs -n 1 git branch -d: perform the deletion of local branches (it won't work for remote ones)Remote
You want to delete remote branches that are already merged to another remote branch. During the deletion, you want to keep some important branches, like HEAD, master, releases, etc.
git branch -r --format "%(refname:short)" --merged origin/master | grep -E -v '^*HEAD$|^*/master$|^*release' | cut -d/ -f2- | xargs -n 1 git push --delete origin
Notes:
-r option and provide the full branch name: origin/mastergrep -E -v '^*HEAD$|^*/master$|^*release' is to match the remote branches that we don't want to delete.cut -d/ -f2- : remove the unneeded 'origin/' prefix that otherwise is printed out by the git branch command.xargs -n 1 git push --delete origin : perform the deletion of remote branches.