How to remove all local git branches but keep master

Published
48

Working with Git is very necessary, but sometimes, a bunch of branches were created during our work, and we want to delete them all.

And a popular question is: how to delete all local Git branches except for the master branch.

Delete a Git branch wont delete the associated commits or data. You just remove the branch out of your local to make your workspace clean.

Delete the local git branch

To delete all local Git branches except for master, you can use the following command:

git branch | grep -v "master" | xargs git branch -D

Let’s breakdown the command:

  • git branch: List all local branches.
  • grep -v "master": Filter the branch list and returns only non-matching lines to the string “master”.
  • xargs git branch -D: Pass the output from the previous command as arguments to git branch -D, deleting the specified branches.

Use the command with caution since it deletes all local branches except master. You can modify the grep command to match the branch names you want to keep.

Delete remote git branch

It’s also worth noting that this command only works for local branches. If you have remote branches that you want to delete, you will need to use a different command.

To delete a remote branch, use the git push command with the --delete flag, like this:

git push origin --delete <branch_name>

This will delete the specified branch from the remote repository. Keep in mind that you will need permission to delete branches on the remote repository, and that other team members may have to update their copies of the repository to reflect the change.

In summary, deleting local Git branches is a simple task that can help keep your repository organized and focused on the current development efforts. Just be sure to use the appropriate command and understand the consequences of deleting a branch before proceeding.