Friday, May 25, 2018

Cleaning up your local repo from too many dead branches

You'll eventually have too branches in your local that's untracked - ex. Not in origin or Github. This gets annoying since too many of these branches are often dead. So time to prune them:

git remote prune origin

You would assume that would work but nope. This only works on the remote repo and not your local. But you can to do this:

git branch --merged master | grep -v '^[ *]*master$' | xargs git branch -d

This is uncomplicated since this just soft deletes all branches that are already merged - the -d flag in git branch.

But if you need to check against the remote repo then a more complex command is called for:

git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk '{print $1}' | xargs git branch -d

The only rub here that is only works on bash or zsh shells. Also you need to run git fetch --prune first because using this.

Powershell

git checkout master; git remote update origin --prune; git branch -vv | Select-String -Pattern ": gone]" | % { $_.toString().Trim().Split(" ")[0]} | % {git branch -d $_}
Reference:

  • https://stackoverflow.com/questions/13064613/how-to-prune-local-tracking-branches-that-do-not-exist-on-remote-anymore/16906759#16906759

No comments:

Post a Comment