Skip to content
GreenSnippets

Delete local Git branches that are already merged

Clean up merged local branches safely, excluding main, master, develop and the current branch.

Bash
git fetch --prune
git branch --merged \
  | grep -Ev '^\*|^\s*(main|master|develop)$' \
  | xargs -r git branch -d

How it works

git branch --merged lists branches whose commits are already in the current branch. The filter protects the branches you never want to delete, and -d (lowercase) refuses to delete anything unmerged. Run it from an up-to-date main.

Preview first by replacing git branch -d with echo. Squash-merged branches do not appear as "merged", so they need manual review. This command has been reviewed but not run through an automated test.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.