To delete all Git branches that have been merged into your current branch, use the following command:
git branch --merged | grep -v "^\*\|main\|master" | xargs -n 1 git branch -d
Explanation:
git branch --merged
: Lists all branches merged into the current branch.grep -v "^\*\|main\|master"
: Excludes:
- The current branch (marked with
*
). - Protected branches like
main
ormaster
.
xargs -n 1 git branch -d
: Deletes each listed branch safely (only if fully merged).
For Branches Merged into main
(or another branch):
# Switch to your main branch first
git checkout main
# Delete all merged branches except 'main'
git branch --merged | grep -v "main" | xargs -n 1 git branch -d
Notes:
- Use
-D
instead of-d
to force delete unmerged branches (⚠️ caution). - Replace
main
with your default branch name (e.g.,master
,develop
). - Add
-r
to include remote branches (e.g.,git branch -r --merged
).
Example Workflow:
# Ensure you're on the main branch
git checkout main
# Pull latest changes to ensure merged status is up-to-date
git pull
# Delete merged branches
git branch --merged | grep -v "main" | xargs git branch -d
For Remote Branches:
To delete merged remote branches (e.g., on origin
):
git fetch --prune
git branch -r --merged | grep -v "main" | sed 's/origin\///' | xargs -I {} git push origin --delete {}
This removes stale remote branches that have been merged into main
.