Git Branch Cleanup Workflow
Identify and delete local branches that have been merged into the main branch to keep the repository tidy and avoid confusion.
Objective
Remove stale local branches after merge to prevent confusion and reduce clutter in the developer environment.
Environment
- A local Git repository with multiple branches
- Git CLI version 2.0 or later
- Shell terminal access
Steps
1. List all local branches
Run git branch to see all local branches and identify which ones exist.
Expected state: A complete list of local branches is displayed.
2. Check merged branches
Run git branch --merged main to identify branches that have been fully merged.
Expected state: Only branches safe to delete are listed.
3. Delete merged branches
Pipe the merged branch list to git branch -d for each branch name excluding main.
Expected state: All merged branches are removed; unmerged branches remain.
Decision points
Should you delete unmerged branches?
- Yes, force delete with -D
- No, keep them until merged
Keep unmerged branches to avoid losing work; only use -D if you are certain the work is disposable.
Expected outcome
All local branches that have been merged into main are deleted, and only active or unmerged branches remain.
Verification
Run git branch again and confirm that no merged branches remain; verify that main and active feature branches are still present.
Cleanup
No cleanup needed beyond the branch deletion itself.
Why clean up branches
Merged branches accumulate quickly and make it hard to find active work. Regular cleanup keeps the branch list meaningful.
git branch --merged main | grep -v "main" | xargs git branch -d
Verification
After cleanup, git branch should show only main and branches with unmerged commits.
Implementation Notes
This workflow provides a structured approach to ensure consistent results across team members and environments.
Common Pitfalls
Skipping verification steps or rushing through the process can lead to incomplete results. Always follow each step in order and verify before proceeding.