With any long-running git project comes a bunch of stale and unused git branches. The list builds up really quickly—the more you experiment, the more stale branches you accumulate. Some get merged, some are just throwaways.
Table of contents
Open Table of contents
Count Your Local Branches
A simple way to count all your local branches under a git repo:
git branch | wc -l
When I ran this for one of my projects, I had 187 branches. In reality, the project only had 5 active branches. 🤯
Prune Remote Branch References
Think about all the branches that have already been removed from the remote repository. Your local copy might still have references to those branches.
git remote prune origin
This removes local references to remote branches that no longer exist.
Delete Stale Local Branches
Step 1: View branches with tracking info
git branch -vv
The -vv argument shows what the last commits were on those branches, plus their remote tracking status.
Step 2: Identify “gone” branches
The interesting part of this output is that it shows local branches that don’t have corresponding branches in remote. They’re marked with the text : gone.
git branch -vv | grep 'origin/.*: gone]'
Step 3: Extract branch names and delete
To delete these branches, extract the first word in each line using awk and pass it to git branch -d using xargs:
git branch -vv | grep 'origin/.*: gone]' | awk '{print $1}' | xargs git branch -d
Manual Branch Deletion
For individual branches:
git branch -d <branch_name>
The difference between -d and -D
-d: Safe delete—only works when changes are fully pushed/merged-D: Force delete—removes the branch regardless of merge status (potential data loss!)
Delete Remote Branches
If you need to delete a branch from the remote:
git push <remote_name> --delete <branch_name>
For example:
git push origin --delete fix_less
Keep your git workspace clean! 🧹