Here’s a quick bash script to delete all local git branches that haven’t seen a commit in the last 12 months - my attempt at cleaning up some cruft on my computer. You can see when branches were last edited via

git for-each-ref --sort=-committerdate --format='%(refname:short) %(committerdate:relative)' refs/heads/

I use a Windows machine so in the end I ended up calling out to Powershell for the date calculation. Perhaps there’s a neater way. You’d certainly want to change the cutoff_date line if you’re not on Windows.

It’s adapted from something Google Gemini wrote and I’m no git expert, so please take extreme care before running it! You can always comment out the git branch -D line if you want to just have it list what it would have deleted rather than actually doing the deleting.


#!/bin/bash

# Time threshold (in months) for considering a branch as old
AGE_LIMIT=12

# Branches to be excluded from deletion (important ones)
EXCLUDED_BRANCHES="master main develop"

# Calculate date for the time threshold (using PowerShell)
cutoff_date=$(powershell.exe -Command "Get-Date -Date \$(Get-Date).AddMonths(-$AGE_LIMIT) -Format 'yyyy-MM-dd'")

# Fetch for updates from remotes
git fetch --all 

# Delete local branches that meet the criteria
git for-each-ref --sort=-committerdate --format='%(refname:short) %(committerdate:short)' refs/heads/ | while read branch date; do
  if [[ $date < $cutoff_date ]]; then
    # Check if the branch is to be excluded 
    if [[ ! $EXCLUDED_BRANCHES =~ $branch ]]; then
      echo "Deleting branch: $branch (last updated on $date)"
      git branch -D "$branch"
    fi
  fi
done