Pruning obsolete Git branches

Working on a larger project and following the GitHub Flow very often leads to a messy local repository. One day you find yourself among tens of dead branches.

How can we clean up that big hairy mess?

Your very first thought might be: "I will use the power of Git and clear my local repository". You run $ git remote update origin --prune or $ git remote prune origin, but nothing significant happens. Your local repository still contains branches you are not willing to exist.

Unfortunately, there's no magic way to get rid of dead Git branches. But, you can write a simple one-liner to do that for you.

$ git fetch -p; for branch in $(git branch -vv | grep ': gone]' | gawk '{print $1}'); do git branch -d $branch; done

Let me explain step by step how it works.

  1. git fetch -p fetches branches and removes any remote-tracking references that no longer exist on the remote.
  2. for branch in $(git branch -vv | grep ': gone]' | gawk '{print $1}'); do git branch -d $branch; done
    2.1 Iterate through the result of $(git branch -vv | grep ': gone]' | gawk '{print $1}'); do git branch -d $branch; done (explained below) and delete local branches.
    2.2 git branch -vv lists branches along with relationship to upstream branch (if any). Prints the name of the upstream branch.
    2.3 grep ': gone]' searches for a pattern : gone] which means that a branch doesn't have a remote-tracking reference, i.e. can be considered obsolete.
    2.4 gawk '{print $1}' prints the first column, a local branch name in our case.

Michael Samoylov

Python, JavaScript and Swift Expert with 12+ years of experience.

Vilnius, Lithuania https://monmar.tech

Subscribe to Michael Samoylov

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!