简体   繁体   中英

Local changes only - How do I delete all remote tracking branches without a corresponding local branch?

Origin of repo I'm working on has hundreds of branches.

I ran a git fetch by accident once and now I have hundreds of remote tracking branches.

I want to delete all the remote tracking branches. I don't want to delete the branches on origin, only the remote tracking branches on my local environment. I also have local branches which I'm managing and don't want the remote tracking branches of my local branches to be deleted.

How do I do this?

{ git for-each-ref refs/heads --format='delete %(upstream)';
  git for-each-ref refs/remotes --format='delete %(refname)';
} | grep ^delete\ refs/remotes | sort | uniq -u | git update-ref --stdin

So that generates delete-the-ref commands for every branch's upstream and for every remote-tracking ref. Any duplicate remotes are some branch's upstream, don't want to delete those (edit: and don't want to delete local upstreams!), so grep ^refs/remotes | sort | uniq -u grep ^refs/remotes | sort | uniq -u grep ^refs/remotes | sort | uniq -u outputs only the remotes that don't show up in both lists. git update-ref --stdin actually has a little command language to handle monster batches of updates like this efficiently.

On MacOS the following shell script deletes all the remote tracking branches if a corresponding local branch does not exist. (modified script from this answer )

branch_not_delete=( "master" "develop")

for branch in `git for-each-ref refs/remotes/origin --format '%(refname:short)' | grep -v HEAD`;  do
    branch_name="$(awk '{gsub("origin/", "");print}' <<< $branch)"
    local_exists="$(git rev-parse --verify $branch_name 2> /dev/null)"

    if [[ -z "${local_exists// }" ]]; then
      if ! [[ " ${branch_not_delete[*]} " == *" $branch_name "* ]]; then
        git branch -d -r origin/$branch_name
      fi
    fi
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM