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

Web Dev

Updating payment method email addresses in Stripe

You can't update the email address associated with a payment method in Stripe via their dashboard, you need to use the Stripe CLI

Ruby

Irreversible Rails Migrations

What are irreversible migrations and how might we use them to our advantage?