Skip to content

Instantly share code, notes, and snippets.

@andrewaylett
Created February 20, 2026 17:49
Show Gist options
  • Select an option

  • Save andrewaylett/27c6a33bd2fc8c99eada60589f0ca31f to your computer and use it in GitHub Desktop.

Select an option

Save andrewaylett/27c6a33bd2fc8c99eada60589f0ca31f to your computer and use it in GitHub Desktop.
A git custom command to clean up unneeded local branches
#!/bin/bash
set -euo pipefail
for branch in $(git branch --format="%(refname:lstrip=2)" --merged)
do
echo "Considering $branch"
if git config branch.$branch.remote
then
# Branch has remote tracking
ORIGIN_NAME=$(git config branch.$branch.remote)
ORIGIN_REF=$(git config branch.$branch.merge)
if git ls-remote --exit-code $ORIGIN_NAME $ORIGIN_REF
then
echo "Remote branch still exists, skipping"
else
echo "Removing branch"
git branch -D $branch
fi
else
echo "Tracking not presnt, assuming not yet pushed"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment