How to Safely Delete All Local Git Branches

Cleaning up your local branches can make your workflow tidier and less confusing. If you want to delete all branches except ones you want to keep (for example, dev
and main
), you can do it with this one-liner:
git branch | grep -v 'dev' | grep -v 'main' | xargs git branch -D
What Each Part Does
git branch
Lists all your local branches.
terminal git:(dev) ✗ git branch
bar
baz
* dev
foo
main
grep -v <branch-you-want-to-keep>
Filters out (-v
) the branches named dev
or main
from the list, so they won’t be deleted.
terminal git:(dev) ✗ git branch | grep -v dev | grep -v main
bar
baz
foo
xargs
Takes each branch name from the filtered list and passes it to the next command.
terminal git:(dev) ✗ git branch | grep -v dev | grep -v main | xargs
bar baz foo
git branch -D
Force-deletes (-D
) each branch given by xargs
.
Warning: This will delete branches even if they haven’t been merged!
terminal git:(dev) ✗ git branch | grep -v dev | grep -v main | xargs | git branch -D
Deleted branch bar (was <some-sha>).
Deleted branch baz (was <some-sha>).
Deleted branch foo (was <some-sha>).
For a safer delete (only deletes merged branches), use git branch -d
instead of git branch -D
.