How to clean up git branches that have already been merged
If you have ever worked on a large programming project that was managed using git (source control), then odds are high that there was a point where you may have ended up with numerous git branches laying around.
Some of the branches might still be being worked on. Some of them might have been merged long ago, and the developer simply forgot to delete the branch. It’s very easy to end up with a lot of clutter!
Fortunately, git has some built-in functions that make solving this problem easy!
To see which branches (except master and your develop branch) have been merged into master and are safe to delete, simply run this command:
1 2 3 |
git checkout master && git pull && git fetch && git branch -r --merged | egrep -v "(^\*|master|develop)" | sed 's/origin\///' | xargs -n 1 echo |
To then delete those branches from your remote server:
1 2 3 |
git checkout master && git pull && git fetch && git branch -r --merged | egrep -v "(^\*|master|develop)" | sed 's/origin\///' | xargs -n 1 git push --delete origin |
To also clean up your local git branchesĀ and delete any local branches that do not exist on remote):
1 2 3 |
git checkout master && git pull && git fetch --prune && git remote update --prune && git branch -vv | grep ': gone]'| grep -v "\*" | awk '{ print $1; }' | xargs git branch -d |
Alternately, if you don’t want to get your hands dirty with low-level commands on the command line, there is a handy little python tool called “git-sweep”, which can be found here: https://github.com/arc90/git-sweep
With git-sweep installed, all you have to do is checkout your “master” branch and run:
1 2 3 |
git-sweep cleanup --skip=develop |
Side note: Yes, I realize that this information can be found quite easily by googling, and this problem has been solved a thousand times over. I’m mainly just writing this post for my own personal reference.