How To Clean Local Git Branches That Were Removed On The Remote?
1 min readSep 25, 2019
There isn’t a simple command to clean your local git branches that were removed on the remote, but… we can create a one!
So if you want to remove local branches, that does not exist any longer on the remote you can run this simple command.
git fetch -p && git branch -vv | grep 'origin/.*: gone]' | awk '{print $1}' | xargs git branch -D
Let’s analyse it step by step.
git fetch -p
— fetch newest information about remote branches and-p
(or--prune
) remove any remote-tracking references that no longer exist on the remote,git branch -vv
list all local branches with a state on a remote repository,grep 'origin/.*: gone]'
grep branches that are no longer present on the remote (marked bygone
marker),awk '{print $1}'
select branches names,xargs git branch -D
remove those branches on the local machine.
That’s it. Remember you can put this command into alias, so it becomes shorter, e.g. gitgone
alias gitgone="git fetch -p && git branch -vv | grep 'origin/.*: gone]' | awk '{print \$1}' | xargs git branch -D"
*beware of escaping $1
in awk part