Maintain your GIT branches clean

post-thumb

We commonly execute a prune to remove all remote branches:

git remote prune origin

While working with Git in Visual Studio, it is common to end up with a bunch of unused branches locally. These branches may include those downloaded for code review and those already submitted as pull requests. Executing a prune removes all remote branches. That leaves them as local branches with no upstream. To remove the branches with no upstream, you can use the following command:

git branch -D $(git branch -vv | grep ': gone]' | awk '{ print $1 }')

Breaking this down, the first part of the command is git branch -D $(<CMD>), this will remove the branch even if Git thinks they have not been merged. If we use $(<CMD>) in bash or PowerShell, will take whatever the output of <CMD> and pass it to git branch -D as the branch name argument.

as <CMD> we are using git branch -vv which returns the branches with verbose details including the relationship to the upstream branch. When the remote has not been found, there will be a “gone” text in the details. grep will filter out the ones with this text and with awk '{ print $1 }', we finally format the results from the verbose details to just the branch name which is exactly what git branch -D needs to remove it from our lists.

Putting it in a single line we could cleanup our list of branch running:

git remote prune origin && git branch -D $(git branch -vv | grep ': gone]' | awk '{ print $1 }')

Related


This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.