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?
Try the following command:
git branch -d $(git branch --merged | 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.
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)
In case you've multiple remotes, add grep origin | before cut to filter only the origin.
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))
Then git fetch the remote again and use the previous git push -vdcommand again.
If you're using it often, consider adding as aliases into your ~/.gitconfig file.
In case you've removed some branches by mistake, use git reflog to find the lost commits.