DEV Community

loading...

Git: How to delete all local branches except master

Andrei Fedotov
I write here some notes
・1 min read

Checkout to master branch.

The command to delete all branches except master is:
git branch | grep -v "master" | xargs git branch -D

To use the same command in Windows we have to install some utilities

Or, we can use PowerShell command that do the same thing that above command do:
git branch | %{ $_.Trim() } | ?{ $_ -ne 'master' } | %{ git branch -D $_ }
or
git branch -D @(git branch | select-string -NotMatch "master" | Foreach {$_.Line.Trim()})
Alt text of image

Discussion (5)

Collapse
vishnumeera profile image
VishnuSankar

thank you so much, just added one more check

git branch | %{$.Trim()} | ?{$ -ne 'master' -and $.Substring(0,1) -ne '*'} | %{git branch -D $}

Collapse
rhartzell profile image
Rod Hartzell

Ha! Sweet. Super simple and super efficient. Thanks for sharing.

Collapse
mahldcat profile image
mahldcat

I did noticed on the first powershell one liner, I did noticed that one of the response lines was:

"error: branch '* master' not found."

Collapse
andreisfedotov profile image
Andrei Fedotov Author

Hi,

I've just checked it again in PowerShell and everything works. I made a quick check like:
git init
git branch new
git branch new2
git branch new3
git branch new4
git branch | grep -v "master" | xargs git branch -D

Just to confirm, are you sure that you installed Gow utilities, input the command correctly and that you are in master branch?

Collapse
ap3rus profile image
Vladislav Nagornyi

It's the PS script which gives this error, as the git branch prefixes selected branch with asterisk:

❯ git branch |`
  %{ $_.Trim() } |`
  ?{ $_ -ne 'master' } |`
  %{ git branch -D $_ }
Enter fullscreen mode Exit fullscreen mode
Deleted branch <branch1> (was <commit1>).
error: branch '* master' not found.
Enter fullscreen mode Exit fullscreen mode

Could be addressed e.g. by adding check for * master:

git branch |`
  %{ $_.Trim() } |`
  ?{ $_ -ne 'master' -and $_ -ne '* master' } |`
  %{ git branch -D $_ }
Enter fullscreen mode Exit fullscreen mode