如何列出已经推送到远程仓库的分支?

4

我可以找到很多列出跟踪分支的答案 (这里),但我想做的是检查哪些本地分支可以安全删除,因为它们的提交已经被推送到远程仓库。

在大多数情况下,我将这些分支推送到远程仓库而它们并没有被“跟踪”,所以那部分并没有什么帮助。然而,在大多数情况下,远程分支具有相同的名称,并且应该指向相同的提交(但不总是正确的)。

似乎这应该是一个很常见的事情吧?


1
这不是一个自动化的解决方案,但你可以针对每个远程分支运行 git branch --merged origin/remotebranch 命令来列出本地分支,其指向可从 remotebranch 的头部到达。 - jub0bs
谢谢@Jubobs,这让我找对了方向... - Matthieu
1个回答

4
我找到的方法是:
git branch -a --contains name_of_local_branch | grep -c remotes/origin

当然,origin可以更改为任何远程名称。
这将输出包含本地分支的远程分支编号。如果该编号与0不同,则可以从本地存储库中清除它。
更新,将其转换为脚本:
#!/bin/bash
# Find (/delete) local branches with content that's already pushed
# Takes one optional argument with the name of the remote (origin by default)

# Prevent shell expansion to not list the current files when we hit the '*' on the current branch
set -f

if [ $# -eq 1 ]
then
  remote="$1"
else
  remote="origin"
fi

for b in `git branch`; do

  # Skip that "*"
  if [[ "$b" == "*" ]]
  then
    continue
  fi

  # Check if the current branch tip is also somewhere on the remote
  if [ `git branch -a --contains $b | grep -c remotes/$remote` != "0" ]
  then
    echo "$b is safe to delete"
    # git branch -D $b
  fi
done

set +f

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接