DEV Community

Ariel Mejia
Ariel Mejia

Posted on

Remove all git local branches except "main"

Working locally would tempt to acummulate a lot of git branches locally, most of the time we want to keep only the "main" branch, to execute this just run:

git branch | grep -v "main" | xargs git branch -D
Enter fullscreen mode Exit fullscreen mode

Explanation

  • The first section git branch list all the branches locally.
  • grep -v "main" filter out from the output branches list the main branch
  • xargs git branch -D runs git branch -D to all the branch items inside the branch list

Happy Coding!

Top comments (6)

Collapse
 
codycodes profile image
Cody Antonio Gagnon

Great to see how easy ‘xargs’ can make things!
Curious if there’s an easy way to also filter out other default branch names like “master”

Collapse
 
viiik profile image
Eduard

You can use grep -Ev 'main|master' the E adds "extended regex" and the main|master is regex for "main or master".

You can also add other regex patterns like "branches that begin with foo-" for example.

Collapse
 
jeffwindhorst profile image
Jeff

egrep for advanced regex.

Collapse
 
eren_yeager_c1759662d1eae profile image
eren yeager

nice

Collapse
 
eren_yeager_c1759662d1eae profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
eren yeager

gjfg j gfj gfj fgj gfj fgjfg j fgj fgj

Some comments may only be visible to logged-in visitors. Sign in to view all comments.