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:
git branch
lists all local branches.grep -v "main"
filters out themain
branch from this list.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! 🔥