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

Freelancing

Getting the most out of your agency

Here are some tips based on years of working with, for, and as an agency on how to get the most out of any work you do.

VS Code Web Dev

Select multiple lines in VS Code

How to select multiple lines to edit at once within VS Code