Delete Git Branches That Have Been Merged

By Dave Ceddia

Got a lot of old git branches hanging around? Here’s a little script that will delete the branches that have been marged.

It’ll print out the branches to be deleted, and then prompt for whether you want to delete them.

If your top-level branch isn’t called “main”, customize the MAIN variable to match.

Script: Delete old git branches

#!/bin/bash

# Change this to match the name of your top level branch
MAIN=main

echo "These branches have been merged into $MAIN and will be deleted:"
echo
git branch --merged $MAIN | grep -v "^\* $MAIN"
echo

read -p "Continue? [y/N] " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]
then
  exit 1
fi

git branch --merged $MAIN | grep -v "^\* $MAIN" | xargs -n 1 -r git branch -d

Copy/paste this into a file in your repo or elsewhere (like git-cleanup.sh) and make it executable with chmod +x git-cleanup.sh

Bonus: if you want this file to be ignored, but you don’t want to clutter up the shared .gitignore file with your own local scripts, you can edit .git/info/exclude and list this file there. That file works as a local gitignore.