How to remove every local branch except the main branch?

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

To remove every local branch except the main branch use git branch | grep -v "main" | xargs git branch -D. The command has three parts, git branch lists all the local branches, grep -v "main" selects every branch except the main one and with xargs git branch -D these branches are deleted.

Make sure to have the main branch checked out before running this command, since the currently checked out branch won't be removed.

To do a dry run and see what branches would be removed use git branch | grep -v "main".

Layer 1
Terminal Example
git branch
  branch-2
  log-changes
* main
  test-branch
  wip-playground

git branch | grep -v "main" | xargs git branch -D
Deleted branch branch-2 (was 120f7ab).
Deleted branch log-changes (was 120f7ab).
Deleted branch test-branch (was 120f7ab).
Deleted branch wip-playground (was 120f7ab).

See git branch to learn more about it.

Last modified on November 30, 2021.

You might also like