4

Suppose I am working alone, and I only use remotes as a code backup solution. There may be times when I might delete local branches.

I know that I can delete specific branches on a remote with git push origin --delete mybranch, but is there a way to delete all remote branches that do not exist locally without having to manually check for branches that do not exist locally?

Flux
  • 9,805
  • 5
  • 46
  • 92
  • 1
    Just write a script that does this. Use `git for-each-ref` (start with `git fetch --prune` to update your Git's remote-tracking branches). – torek Sep 01 '17 at 22:47
  • @torek is correct, that is probably the best way, but you've piqued my interest, as this is the polar opposite of the general practice, what is your use case that you would not want to keep the code? – LightBender Sep 02 '17 at 00:30
  • @LightBender I usually do local commits followed by pushes of all branches to a remote. Sometimes when working offline, I merge branches, and then I delete the old (merged) branches. However, the old (merged) branches will still be present on the remote. I'm looking for ways to keep local and remote in sync for this kind of workflow. – Flux Sep 02 '17 at 01:16
  • that makes more sense, what remote are you using? – LightBender Sep 02 '17 at 02:05
  • @LightBender Currently using GitHub remotes. – Flux Sep 02 '17 at 02:23

1 Answers1

2

Sometimes when working offline, I merge branches, and then I delete the old (merged) branches.

It is best to do so online, as you can follow up with a push --delete, as in this answer:

git branch -r --merged | grep -v master | sed 's/origin\///' | xargs -n 1 git push --delete origin

But since you deleted your branch locally (offline), you need, when online, to fetch --prune the remote branches from GitHub, check if their local counterpart does exist, and push --delete otherwise.

Use git for-each-ref with the refname:lstrip=3 format in order to list the short names of those remote branches:

 git for-each-ref --format='%(refname:lstrip=3)' refs/remotes/origin

You can check if a local branch does exists with git show-ref --quiet

if git show-ref --quiet refs/heads/develop; then
    echo develop branch exists
fi

So you can easily combine the two.

git fetch --prune
for branch in $(git for-each-ref --format='%(refname:lstrip=3)' refs/remotes/origin); do
    if ! git show-ref --quiet refs/heads/${branch}; then
        echo "delete remote branch '${branch}'"
        git push origin --delete ${branch} 
    fi
done
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250