Git

How to Delete all Git Branches Except master or main

While working on some development projects on Git, programmers create a bunch of branches for different modules and features locally. However, some of them do not work properly, or after completing the task, developers want to delete them just to free-up space. For this purpose, it is required to delete all remaining branches, excluding the master or main branch.

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:

$ git switch main

Step 2: List Git Local Branches

Next, execute the below command to view the all branches list:

$ git branch

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”:

$ git branch | grep -v "master\|main" | xargs git branch -D

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:

$ git branch

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.

About the author

Maria Naz

I hold a master's degree in computer science. I am passionate about my work, exploring new technologies, learning programming languages, and I love to share my knowledge with the world.