how to remove all local branches in git except master/main
- User
how to remove all local branches in git except master/main
- Assistant
To remove all local branches in a Git repository except for the
masterormainbranch, you can use the following command sequence in your terminal. First, make sure you are currently on the branch you want to keep (eithermasterormain). Then you can run the following commands:-
Switch to the
masterormainbranch:bashgit checkout master # or git checkout main -
Delete all local branches except
masterormain: You can use the following one-liner:bashgit branch | grep -v "master" | grep -v "main" | xargs git branch -d
-
- User
too complicated isnt it? is there any native git command to do this?
- Assistant
While there isn't a single native Git command that directly deletes all branches except for the specified ones (
masterormain), you can simplify the process by using a combination of Git commands more intuitively. However, there is no built-in command likegit branch --delete-all-exceptfor this purpose.Here's a streamlined approach without using
greporxargsby leveraginggitbuilt-in options more effectively:-
Check out to the branch you want to keep (either
masterormain):bashgit checkout master # or git checkout main -
Use a loop in a script or one-liner: You can run a simple loop in the bash shell:
-
- User
is it good practice to delete unused branches?
- Assistant