Flux
Flux

Reputation: 10920

Delete remote branches that do not locally exist

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?

Upvotes: 4

Views: 855

Answers (1)

VonC
VonC

Reputation: 1324013

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

Upvotes: 2

Related Questions