How do I delete all Git branches which have been merged?

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:

  1. git branch --merged: Lists all branches merged into the current branch.
  2. grep -v "^\*\|main\|master": Excludes:
  • The current branch (marked with *).
  • Protected branches like main or master.
  1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *