Delete local GIT branches that were deleted on remote repository

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.

Here is a command that will delete all local branches that are not present anymore in the remote repository:

git branch -vv | grep ' gone]' | awk '{print $1}' | xargs 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.

awk '{print $1}'

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

xargs 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.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.