DEV Community

Vineeth.TR
Vineeth.TR

Posted on

๐Ÿงน How to Delete All Local Git Branches Except the Current One

Working with Git for a while? Your local repository might be cluttered with old branches you no longer need.

counting

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
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  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
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“‹ git branch

Lists all local branches, like so:

  feature/login
  feature/profile
* main
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”Ž 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
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

Then just run:

git-clean-branches
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ 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
Enter fullscreen mode Exit fullscreen mode

Just one command and your local branches are tidy again. ๐Ÿ‘Œ

Top comments (0)