I frequently search for the code to delete all local branches except master so I can copy/paste the result, but I always get the "master" version of this โ which doesn't help the copy/paste part of it.
$ git branch | grep -v "main" | xargs git branch -D
Here's hoping this becomes the top result so I can speed up my process by one second. We all know I'll never actually remember the command.
Happy coding!
Latest comments (18)
omg thanks :)
most of my local branches have a prefix. So when i needed to cleanup all the local branches except the prod ,i have an alias set as
git_branch_delete="git branch | grep $@ | xargs git branch -D". So i just dogit_branch_delete flipand deletes all branches starting withflipprefixmake an alias out of it which also protect master and dev branches,
and also try to delete them in safer way with -d instead of -D.
git branch --mergeddoesn't work well if your team uses GitHub squash commits to merge PRs: stackoverflow.com/a/19309568/771768I've had a lot of success with my script that:
If you want to delete only branches that have been deleted remotely then
git fetch --pruneis an optionNice. Just one thing; it only deletes local ones.
You can create an alias function like this:
used:
git removeLocalsor if you want to account for master vs main
used:
git removeLocals mainI recommend not doing the second one as you may accidentally remove your local version of main/master due to a typo
You could also just make two aliases removeLocalsMain and removeLocalsMaster
i think instead of main
$(git_main_branch)should be helpfulThat's a great tip! Thanks!
Every time I successfully use
xargsI spend the next several hours thinking "whoa, I did anxargs". It somehow never gets old.Solid
xargs, good stuff.One observation to be made is if you for some reason has another branch that has "main" as part of its name, this command would not delete it. Maybe
grep -v "^\*\? *main$", but then its getting already too complicated... ๐