Cleaning Up Branches
Branch Cleanup Strategies
Cleaning up branches is essential for maintaining a clean and manageable repository. This process involves removing unnecessary, merged, or stale branches.
Local Branch Deletion
## Delete a fully merged local branch
git branch -d branch-name
## Force delete an unmerged branch
git branch -D branch-name
## Delete multiple branches
git branch -d branch1 branch2 branch3
Remote Branch Cleanup
## Delete a remote branch
git push origin --delete branch-name
## Prune remote tracking branches
git remote prune origin
Batch Cleanup Methods
## Delete all merged branches except main and develop
git branch --merged | grep -v -E 'main|develop' | xargs -r git branch -d
## Remove branches merged into main
git branch --merged main | grep -v main | xargs -r git branch -d
Cleanup Strategies Comparison
Strategy |
Scope |
Risk Level |
Use Case |
Selective Deletion |
Manual |
Low |
Careful cleanup |
Batch Deletion |
Automated |
Medium |
Large repositories |
Force Deletion |
Comprehensive |
High |
Aggressive cleanup |
Interactive Cleanup Script
#!/bin/bash
## Interactive branch cleanup script
## List branches not merged to main
echo "Branches not merged to main:"
git branch --no-merged main
## Prompt for cleanup
read -p "Do you want to delete these branches? (y/n) " response
if [[ $response == "y" ]]; then
git branch --no-merged main | xargs -r git branch -D
fi
Branch Lifecycle Visualization
gitGraph
commit
branch feature-branch
commit
checkout main
merge feature-branch
branch stale-branch
commit
checkout main
branch another-branch
commit
Best Practices
- Regularly review and clean branches
- Use descriptive branch names
- Implement a branch lifecycle policy
- Communicate with team before major cleanups
At LabEx, we recommend a systematic approach to branch management to maintain a clean and efficient repository structure.