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

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

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


当前回答

如果你正在使用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
    }

其他回答

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

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

您可以使用git签出,即。“签出当前分支”。如果存在当前分支的跟踪信息,这是一个没有副作用的操作。

$ git checkout 
Your branch is up-to-date with '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
    }

改进这个答案,我想出了这些.gitconfig别名:

branch-name = "symbolic-ref --short HEAD"
branch-remote-fetch = !"branch=$(git branch-name) && git config branch.\"$branch\".remote || echo origin #"
branch-remote-push  = !"branch=$(git branch-name) && git config branch.\"$branch\".pushRemote || git config remote.pushDefault || git branch-remote-fetch #"
branch-url-fetch = !"remote=$(git branch-remote-fetch) && git remote get-url        \"$remote\" #"  # cognizant of insteadOf
branch-url-push  = !"remote=$(git branch-remote-push ) && git remote get-url --push \"$remote\" #"  # cognizant of pushInsteadOf
git branch -r -vv

将列出所有分支,包括远程分支。