Here are several ways to delete all branches except main:
Delete all local branches except main
Safe approach:
git branch | grep -v "main" | xargs git branch -D
Or if you're currently on main:
git branch | grep -v "\*" | xargs git branch -D
More explicit version
git branch | grep -v -E "main|\*" | xargs -r git branch -D
The -E flag allows extended regex, and -r prevents xargs from running if there's no input.
Step-by-step approach
First, switch to main:
git checkout main
Then delete all other branches:
git branch | grep -v "main" | xargs git branch -D
If you also want to clean up remote tracking branches
git branch -r | grep -v "main" | sed 's/origin\///' | xargs -r git push origin --delete
All-in-one command
git checkout main && git branch | grep -v "main" | xargs git branch -D
Important notes:
- Using
-D(capital D) force deletes branches, even if they have unmerged changes - Using
-d(lowercase d) only deletes merged branches (safer) - Always make sure you're not deleting branches with important unmerged work
- Consider running
git branchfirst to see what branches exist before deleting them
If you want the safer version that only deletes merged branches:
git checkout main && git branch --merged | grep -v "main" | xargs git branch -d