How to delete all Git branches except master or main exampleb
When an exhaustive sprint comes to an end, or a milestone release makes its way out the door, a cleanup routine many developers like to perform is the deletion of all Git branches except the master or main branch in the local repository.
Often this task is performed by doing one local branch delete at a time, but daisy chaining a grep command along with a force branch deletion call can get this task done in a single line of code.
Delete all branches except master command
To delete all branches in your Git repository except master, simply issue the following command:
$ git branch | grep -v "master" | xargs git branch -D
If you want to delete branches such as master-prod, master-test or master-ui, you can adjust the RegEx used by the grep as follows:
$ git branch | grep -v " master$" | xargs git branch -D
If deleting every Git branch except master is a task you commonly run, it might be a good idea to set up an an alias that simplifies the task of issuing the command.
Remove all Git branches but main
Newer Git repositories have renamed the master branch to main.
To delete all branches in Git except main, simply replace the grep for master with a grep for main:
git branch | grep -v "main" | xargs git branch -D
git branch | grep -v " main$" | xargs git branch -D
All branch deletion error
It’s worth noting that you can’t delete a branch that has been checked out. So make sure you are on either the master or the main branch when you run the command that deletes all other branches, otherwise you will run into an error when Git tries to delete the branch that you currently have checked out.
Local vs remote branch deletes
This command only works on your local repository. It will not delete remote branches from GitHub or GitLab, so from that perspective, it is a safe operation to run. However, if you do want the local branch deletions to be reflected in GitLab or GitHub, you’ll need to do some extra work. To remove all remote branches that have been merged into master or main on the remote repo, a command like this would need to be issued:
git branch -r --merged master | ack -v master | sed -e 's/\// :/' | xargs -n2 git push
Good housekeeping is the hallmark of a well rounded software developer. Keep your Git repository nicely pruned, and when the time comes to remove every Git branch except master, this helpful little Git command will surely come in handy.