How to delete local git branches when you delete remote branches

So whenever I work with a git repo with any org, the first thing I look at it is, do they delete their remote branches.

If they don’t, I judge them for not knowing Git and GitHub how powerful it is, and their lack of understanding of git.

I am always a proponent of clean git repo with only active branches, or maybe have branches that might be worked in the future but they should be rebased/merged at least once a month to make sure they don’t become stale.

But when we delete remote branches(through settings in Github post merge) we actually don’t delete local branches, they continue to grow and pollute our local environment. So when I start to check out from one branch to another branch it becomes harder and harder to find the last branch I was working on

So I wanted to delete all local branches that are gone in the remote. After much searching, I found this

git branch --v | grep "\[gone\]" | awk '{print $1}' | xargs git branch -D

This command when run in conjunction with

git fetch origin --prune 

Should get rid of the local branches. The command above is summarised here.

  • git branch --v lists the local branches verbosely
  • grep "\[gone\]" finds all the branches whose remote branch is gone
  • awk '{print $1}' outputs only the name of the matching local branches
  • xargs git branch -D deletes all the matching local branches

This should get rid of the local branches and make your local squeaky clean.

Give me a thumbs up if you would like more such tips.

Saras Arya

Written by

Serverless Junkie, Learning Both React and Devops

Equilibrium

Life isn’t about good or bad, it’s about how good or how bad

Saras Arya

Written by

Serverless Junkie, Learning Both React and Devops

Equilibrium

Life isn’t about good or bad, it’s about how good or how bad