In this study, we will talk about the procedure to delete all Git branches except master or main!
How to Remove all Git Branches Except main or master?
If developers want to delete all local branch excerpt master or main, then firstly, it is required to switch to the main or master from other branches because the current working branch does not get deleted. After that, view all existing branches using the “$ git branch” command. Next, delete all branches and again check the Git local directory branches list for verification.
Check out the below-given steps for implementation of the given scenario!
Step 1: Switch Branch
First, switch to the “main” branch from another Git branch:
Step 2: List Git Local Branches
Next, execute the below command to view the all branches list:
As you can see that, we have multiple branches other than “main” and “master” branches:
Step 3: Delete All Branches Except main and master
Finally, execute the below-provided command to delete all branches except “main” and “master”:
Here, “$ git branch” will list all Git branches, the “grep -v” will filter out the specified branches, for instance, the “main” and “master”, and the “xargs git branch” utilized to pass the filtered branch name to the Git command:
Step 4: List Local Branches
Lastly, we will verify the deleted operation using provided command:
According to below output, we have successfully deleted all branches except “main” and “master” commands:
That’s all! We have efficiently compiled the easiest of deleting all Git branches except “main” and “master”.
Conclusion
To delete all Git branches except the specified branches, first, switch to the “main” or “master” branches, then display all existing branches using the “$ git branch” command. After that, delete all branches by executing the “$ git branch | grep -v “master\|main” | xarg git branch -D” command, and lastly, again, check the Git local directory branches list for verification. This study explained the procedure of removing all Git branches except master or main.