Git Alias to Delete All Merged Branches

Create a git alias that safely deletes all local branches that have been fully merged into the current branch, excluding main, master, and develop.

Cleanup Aliases

Detailed Explanation

Delete Merged Local Branches

After feature branches are merged, the local copies linger. This alias safely removes them all at once:

[alias]
    cleanup = !git branch --merged | grep -v '\*\|main\|master\|develop' | xargs -n 1 git branch -d

Breaking Down the Command

This is a shell pipeline (prefixed with !) with three stages:

  1. git branch --merged lists all local branches whose tips are reachable from HEAD (i.e., fully merged into the current branch)
  2. grep -v '\*\|main\|master\|develop' filters out the current branch (*), main, master, and develop to protect them from deletion
  3. xargs -n 1 git branch -d feeds each remaining branch name to git branch -d for safe deletion

Safety Guarantees

The -d flag (lowercase) only deletes branches that are fully merged. If a branch has unmerged commits, git refuses to delete it and shows an error. This prevents accidental data loss.

Example

# Before cleanup
git branch
#   feature/login
#   feature/payments
#   fix/typo
# * main

git cleanup
# Deleted branch feature/login (was a1b2c3d).
# Deleted branch feature/payments (was e4f5g6h).
# Deleted branch fix/typo (was i7j8k9l).

# After cleanup
git branch
# * main

Customizing Protected Branches

Modify the grep -v pattern to protect additional branches specific to your workflow:

[alias]
    cleanup = !git branch --merged | grep -v '\*\|main\|master\|develop\|staging\|release' | xargs -n 1 git branch -d

Dry Run

To see what would be deleted without actually deleting:

git branch --merged | grep -v '\*\|main\|master\|develop'

Use Case

Run this alias after merging pull requests or at the end of each sprint to clean up completed feature branches. It keeps your local branch list manageable and avoids confusion about which branches are still active.

Try It — Git Alias Builder

Open full tool