Cleaning up Local Git Branches

If you follow the GitHub flow of creating branches, making PRs, merging and then deleting merged branches, you'll inevitably accumulate a number old branches in your local git cache. Periodically, I find myself going through cleaning out branches on my local system. On top of that it can be difficult to figure out which branches are still active.

A coworker shared script with me that he used to clean up his local branches. I created a bin script that allows me to just run gitprune in any git repo folder. The script detects local branches that have been deleted from the remote and then deletes the branches locally. The script is super simple and I'm just putting it up here for reference in the future.

First, create a file name ~/bin/gitprune with the following content.

git fetch -p
git branch -vv | gawk '/: gone]/{print $1}' | xargs git branch -D

On Linux the ~/bin directory is included in your path be default. We just need to make the script executable.

sudo chmod +x ~/bin/gitprune

Finally, you'll need to logout and log back in for the script to be picked up.