Delete local GIT branches that were deleted on remote repository

KC Müller
2 min readSep 12, 2017

--

In my company we are using GitHub to manage our branches. Normally a branch is deleted manually on GitHub a few months after it was merged. So there are not many branches listed on GitHub. But all developers have to clean up the branches on their local machines. If this is not done regularly it can result in a lot of dead branches.

A “git prune” will only remove the remote tracking, but it will not delete the local branch on your machine. Here is a command that will delete all local branches that are not present anymore in the remote repository:

Disclaimer: This is just meant as an example. I do not take any responsibility for the results of executing this code.

git branch -vv | grep ': gone]'|  grep -v "\*" | awk '{ print $1; }' | xargs -r git branch -d

Let me quickly explain what it does:

git branch -vv

will list your local branches and show information about the remote branch, saying “gone” if it is not present anymore.

grep ': gone]'

will fetch the branches that match the “: gone]” phrase.

grep -v "\*"

will fetch only lines that do not contain an asterisk. This will ignore the branch you are currently on and also prevent that the “git branch -d” is executed with a “*” at the end which would result in deleting all your local branches.

awk '{print $1}'

will fetch the output until the first white space, which will result in the local branch name.

xargs -r git branch -d

will use the output (branch name) and append it to the “git branch -d” command to finally delete the branch. If you also want to delete branches that are not fully merged, you can use a capital “D” instead of “d” to force delete.
Because of the “-r” parameter, the command is not executed if there is no input / branch name.

Thanks to jacek.strongowski@strongops.de for giving his input.

--

--