How To Clean Local Git Branches That Were Removed On The Remote?

Dariusz Mydlarz
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.

  1. 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,
  2. git branch -vv list all local branches with a state on a remote repository,
  3. grep 'origin/.*: gone]' grep branches that are no longer present on the remote (marked by gone marker),
  4. awk '{print $1}' select branches names,
  5. 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

--

--

Dariusz Mydlarz

Software Engineer keen on delivering best value for the business