参见: 如何查看哪个Git分支正在跟踪哪个远程/上游分支?

如何知道本地分支正在跟踪哪个远程分支?

我是否需要解析git配置输出,或者是否有一个命令可以为我做这件事?


当前回答

列出本地和远程分支:

$ git branch -ra

输出:

  feature/feature1
  feature/feature2
  hotfix/hotfix1
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/develop
  remotes/origin/master

其他回答

如果你正在使用Gradle,

def gitHash = new ByteArrayOutputStream()
    project.exec {
        commandLine 'git', 'rev-parse', '--short', 'HEAD'
        standardOutput = gitHash
    }

def gitBranch = new ByteArrayOutputStream()
    project.exec {
        def gitCmd = "git symbolic-ref --short -q HEAD || git branch -rq --contains "+getGitHash()+" | sed -e '2,\$d'  -e 's/\\(.*\\)\\/\\(.*\\)\$/\\2/' || echo 'master'"
        commandLine "bash", "-c", "${gitCmd}"
        standardOutput = gitBranch
    }

这是一个命令,给你所有的跟踪分支(配置为'pull'),请参阅:

$ git branch -vv
  main   aaf02f0 [main/master: ahead 25] Some other commit
* master add0a03 [jdsumsion/master] Some commit

您必须费力地浏览SHA和任何长包装提交消息,但它可以快速输入,并且我在第三列中垂直对齐跟踪分支。

如果你需要每个分支的“拉”和“推”配置的信息,请参阅git remote show origin上的另一个答案。


更新

从git 1.8.5版本开始,你可以用git status和git status -sb来显示上游分支

git branch -vv | grep 'hardcode-branch-name'
# "git rev-parse --abbrev-ref head" will get your current branch name
# $(git rev-parse --abbrev-ref head) save it as string
#  find the tracking branch by grep filtering the current branch 
git branch -vv | grep $(git rev-parse --abbrev-ref head)

Git-status瓷器(机器可读)v2输出如下所示:

$ git status -b --porcelain=v2
# branch.oid d0de00da833720abb1cefe7356493d773140b460
# branch.head the-branch-name
# branch.upstream gitlab/the-branch-name
# branch.ab +2 -2

并且只得到上游分支:

$ git status -b --porcelain=v2 | grep -m 1 "^# branch.upstream " | cut -d " " -f 3-
gitlab/the-branch-name

如果分支没有上游,上面的命令将产生一个空输出(或者使用set -o pipefail失败)。

另一个方法(感谢osse),如果你只是想知道它是否存在:

if git rev-parse @{u} > /dev/null 2>&1
then
  printf "has an upstream\n"
else
  printf "has no upstream\n"
fi