How to clean up branches in local Git repository

The git branches in local repository will grow rapidly if you are using branch development, e.g. always create a new branch for any new feature/story/bug-fix.

The branch becomes useless after it merged to master, here’s some commands to clean up branches in local repository.

Remove remote branches which have been deleted on remote repository

Using any of the following commands to remove branches which have been deleted on remote repository, e.g. branch deleted after merge to master

  git fetch --prune
  git pull --prune

If you are on git 1.8.5+ you can set this action to happen during each pull

git config fetch.prune true

Remove local branches which not following remote branch

List local branches which not following remote branch

git branch -vv | grep '\[origin/[^ ]*: gone\]' \
  | tr -s ' ' | cut -d' ' -f2 | grep -v master

Remove the above branches

git branch -vv | grep '\[origin/[^ ]*: gone\]' \
  | tr -s ' ' | cut -d' ' -f2 | grep -v master \
  | xargs git branch -d 

Leave a Reply

Your email address will not be published.