Cleaning up stale Git branches
It’s easy to forget to delete branches once they’ve been merged back to develop
, and over time you can end up with many unused branches cluttering up your git repo.
This command can be helpful to review which branches need deleting. It produces a list of [author] - [last commit date] - [branch name]
.
git for-each-ref --sort=committerdate --sort=committername refs/remotes/ \
--format='%(committername) - %(committerdate:short) - %(refname:short)'
Alternatively, to produce a CSV file of all branches:
git for-each-ref --sort=committerdate --sort=committername refs/remotes/ \
--format='%(committername),%(committerdate:short),%(refname:short)' > branches.csv
Here’s a shell command that will find branches with commits not from this year (2020) and delete them
git for-each-ref refs/remotes/ --format='%(committerdate:short) %(refname:short)' \
| grep -v '^2020-' \
| grep -v -E 'origin/(master|develop)$' \
| cut -d' ' -f2 \
| sed 's/origin\///' \
| xargs git push origin --delete
Taking this line by line:
-
List all branches, and the date of their last commit as
[date] [branch]
-
Filter out any branches with commits in the year 2020
-
Make sure to exclude the
master
anddevelop
branches, in case this repo is stale (wouldn’t want to delete those! Also, you should have them setup as protected branches in Github) -
Split on the space character, and output the second field (the branch names)
-
Remove
origin/
from the branch names -
Delete the branches