Delete All Local Branches Except a Specific Branch in Git

Over time, the number of branches can accumulate, leading to clutter.

Cleaning up these branches is often necessary, but you might want to keep certain branches intact, like the "main" or "develop" branch.

Here's a handy tip on how to delete all local branches except for a specific branch.

Let me copy and paste already!

First, decide which branch you want to keep. For this example, let's assume you want to keep the main branch.

The command to delete all branches except the main branch is as follows:

# Switch to 'main' branch first
git checkout main

# Delete all branches except 'main'
git branch | grep -v "main" | xargs git branch -d

Quick tip: If you want to save multiple branches, just grep more branches like this:

git branch | grep -v "main" | grep -v "develop" | grep -v "another-branch" | xargs git branch -d

This command works in three parts:

  1. git branch lists all local branches.
  2. grep -v "main" filters out the main branch from this list.
  3. xargs git branch -d deletes all branches that are passed to it from the previous command.

Important Notes

  • Ensure you are not currently checked out on a branch you are trying to delete.
  • The -d option safely deletes the branch, which prevents deletion if changes are not merged into an upstream branch. To force delete, you can use -D instead.
  • Always double-check the branches you are deleting to avoid accidental loss of work.

Happy coding! 🔥

Git
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.