Drew Youngwerth's Blog

Code, Art and the Universe.


Git Branch Housekeeping

23 March 2022

I have a bad habit of not deleting my local branches once I'm done with them. After awhile my branch list starts to look like this:

drew/c-3950-provider-frontend
drew/c-4046-frontend-support-for-okta-sign-in
drew/c-4120-improve-add-an-integration-to-a-channel
drew/c-4148-include-language-installation
drew/c-4160-confirm-invite-cannot-read-property
drew/c-4270-add-sdk-installation-instructions-to
drew/c-4388-increment-untitled-notifications-on
drew/c-4392-increment-untitled-automations-on
drew/c-4512-prevent-team-updates-when-provisioning
drew/c-4747-new-routing-ui-with-api-v2-defaults
drew/c-4785-support-sub-routing-strategy-in-default
drew/c-4810-tooltip-in-generate-new-api-key-shows-a
# ... A million more branches

Deleting Merged Branches

A quick and easy way to delete any merged branches is to run:

# List branches merged into current branch | filter out main and dev branch | delete merged branches
git branch --merged | egrep -v "(^\\*|main|dev)" | xargs git branch -d

This works for some people. However, when PRs are squash merged into main, git branch --merged doesn't always seem to show the PR as merged. This prevents the branch from being deleted.

Interactively Deleting Branches

In my case I found it easier to export all local branches into a file with:

git branch --sort=-committerdate | egrep -v "(^\\*|main|dev)" > branches.txt
# Sort is optional but makes it easier to find branches that are still active by putting them towards the top of the list.

From there edit the file and remove any branches that should be kept. Be sure to remove any branches that are still in use. Then delete all branches still in the file with:

cat branches.txt | xargs git branch -d