Steps to Delete All Local Branches in Git
Step 1: Check the list of branches.
Open the GitHub repository’s local directory in your git bash. This repository contains the branches that you want to delete. For example, we have created a test repository and this repository contains 4 local branches and a main branch.
git branch
Step 2: Switch to the main branch
Our task is to delete all local branches and keep the main branch safe. Before running the command to delete, make sure you are switched to the main branch and all the changes are safely merged. To switch to the main branch, open up the editor’s terminal and type the following command:
git checkout main
Step 3: Delete all the remaining branches
The following command will delete all local branches and keep the main branch safe. Run the following command in your terminal to see the changes:
git branch | grep -v "main" | xargs git branch -D
The command to delete all local branches except the main branch involves several Git utilities combined in a single line.
git branch
: This command lists all the local branches in the repository.grep -v "main"
: This is a filter command that excludes the main branch from the list. The-v
option inverts the match, so it selects all lines that do not contain the specified pattern, which in this case is “main”.xargs git branch -D
:xargs
is a command that takes input from standard input and converts it into arguments for another command. In this case, it takes the list of branch names (excluding the main branch) and passes them as arguments togit branch -D
, which deletes each branch.
Step 4: Now if you check branches, you will only find main.
How to Delete All Local Branches in Git?
Git provides a powerful version control system that allows developers to collaborate efficiently on projects. Over time, however, a repository can have a lot of local branches that are no longer needed, cluttering the workspace and potentially causing confusion.
The “main” is the by default branch created in all git repositories. All the other branches can be merged into the main branch. Deleting all local branches after merging them into the main branch allows us to keep the repository clean.