Who has a repository without dead, already merged branches? Admit it, almost no one. In my team, especially since we moved to git flow1, this rarely happens. Forgetting to delete a merged branch from the remote is common, it happens to everyone. But
I believe a tidy repository should let you understand its status at a glance.
After some research, I ended up with the following command to delete all the merged remote branches in one go:
git fetch --prune
git branch -r --merged origin/main |
grep -v ' -> ' |
grep -vE 'origin/(main|develop)$' |
sed 's#^ *origin/##' |
xargs git push origin --delete
Step by step:
git fetch --pruneupdates your remote branches and removes the ones already deleted on the remote.git branch -r --merged origin/mainlists the remote branches already merged intomain.grep -v ' -> 'skips theorigin/HEAD -> origin/mainline.grep -vE 'origin/(main|develop)$'protects the long-lived branches. Add any other branch you want to keep here. I once deleteddevelopby mistake, so be careful.sedremoves theorigin/prefix.xargs git push origin --deletedeletes what is left.
Today, if you use GitHub, you can turn on Automatically delete head branches in the repository settings, and merged pull request branches are deleted for you. For local branches, I later built git-branch-switcher, which can delete several branches at once.
Footnotes
-
Unfortunately, git flow does not delete branches once they are merged. This could be a good thing if, like me, you like to mess up your work playing with rebase and squash. ↩