Working with Git for a while? Your local repository might be cluttered with old branches you no longer need.
If you're tired of cleaning them one by one, here's a one-liner to delete all local Git branches except the one you're currently on. 🧼
✅ The Command
git branch | grep -v "$(git rev-parse --abbrev-ref HEAD)" | xargs git branch -D
🧠 What It Does
Let's break it down step by step:
🔍 git rev-parse --abbrev-ref HEAD
This gives you the name of the current branch you're on.
main
📋 git branch
Lists all local branches, like so:
feature/login
feature/profile
* main
🔎 grep -v "$(git rev-parse --abbrev-ref HEAD)"
This removes (filters out) the current branch from the list. -v
means "exclude matching lines".
🧹 xargs git branch -D
This force-deletes (-D
) each branch passed in from the previous output.
⚠️ Warning
This command will force delete all local branches except your current one. That means:
- Any unmerged changes in those branches will be lost.
- This does not affect remote branches.
- Use with caution.
If you want to be safe, replace -D
with -d
:
git branch | grep -v "$(git rev-parse --abbrev-ref HEAD)" | xargs git branch -d
This will only delete branches that have been merged into the current branch.
📦 Pro Tip: Make it an Alias
If you find yourself using this often, add it to your shell aliases:
alias git-clean-branches='git branch | grep -v "$(git rev-parse --abbrev-ref HEAD)" | xargs git branch -D'
Then just run:
git-clean-branches
🚀 Summary
When you're done with old branches and want to keep your workspace clean, this one-liner saves you from deleting each branch manually.
No more:
git branch -d branch1
git branch -d branch2
Just one command and your local branches are tidy again. 👌
Top comments (0)