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.
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:
git branch --mergedlists all local branches whose tips are reachable from HEAD (i.e., fully merged into the current branch)grep -v '\*\|main\|master\|develop'filters out the current branch (*), main, master, and develop to protect them from deletionxargs -n 1 git branch -dfeeds each remaining branch name togit branch -dfor 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
Related Topics
Git Alias to Prune Stale Remote Tracking Branches
Cleanup Aliases
Git Alias to Delete Branches with Gone Remotes
Cleanup Aliases
Git Aliases for Branch Listing and Management
Branch Aliases
Git Alias for Checkout and Branch Shortcuts
Branch Aliases
Git Alias Best Practices and Organization Tips
Best Practices