Quickly tidy up old git branches

How to quickly tidy up your local and remote git branches

I am always forgetting how to tidy up my orphaned git branches, which over time can cause various apps which care about the branches you have to become sluggish.

Clean merged branches

This will remove references to local branches which have been merged.

Replace master, main and dev, or add additional branches that you care about to not want to get deleted regardless of merge status.

  git branch --merged | egrep -v "(^\*|master|dev|main)" | xargs git branch -d

Here is the high-level explanation;

  • git branch --merged returns branches you have locally which have been merged into the main branch
  • These get piped to the egrep command, which filters out specific branches, in our case master|dev|main
  • This now smaller list of branches gets piped to xargs, which takes a series of inputs (our branch names) and gives it to git branch -d
  • git branch -d branch-name will delete the branch called branch-name

I have this command in a TextExpander shortcut, but you could easily have this has a bash or git alias if useful.

Clean up remote branches

This will remove references to deleted upstream branches.

  git remote prune origin

Video on cleaning merged branched in git

If you prefer to watch videos on this sort of thing here you go!

Recent posts View all

MacProductivity

Some Mac Tips

Some settings or tips I've learned over the years to make using your Mac an even nicer experience

Writing Git

How to speed up Rubocop

A small bit of config that could speed up your Rubocop runs