DEV Community

Wahid Abduhakimov
Wahid Abduhakimov

Posted on

Remove local stale branches

It's no secret that we end up with tons of unused, stale branches (either merged or not) in local git repository.

You might want to clean-up unused branches for both organization and storage purposes. But you don't want to delete branches one-by-one which would literally take hours (sometimes).

Here is how to remove local branch in bulk.

1. Remove git branches on *nix terminal.

# this will delete only merged branches
git branch --merged | grep -v \* | xargs git branch -D

# this will delete all branches except the current one checked out
git branch | grep -v \* | xargs git branch -D
Enter fullscreen mode Exit fullscreen mode

2. Remove git branches on Windows Powershell/Terminal.

# this will magically all branches except dev, main, master and develop.
git branch | Select-String -Pattern '^(?!.*(dev|main|master|develop)).*$' | ForEach-Object { git branch -D $_.ToString().Trim() }

# this will only delete merged branches.
git branch --merged | Select-String -Pattern '^(?!.*(dev|main)).*$' | ForEach-Object { git branch -D $_.ToString().Trim() }
Enter fullscreen mode Exit fullscreen mode

Yeah, it's that easy. Go ahead and give your local git some breathe 🙂.

Top comments (0)