默认远程获取 git fetch

24

如果我在一个本地分支上,该分支跟踪任何远程分支,并且我执行以下命令:

git fetch

假设我在$GIT_DIR/config中定义了几个远程仓库,从哪个远程仓库进行获取fetch操作?

我尝试从手册页面中找到答案,但是这一点对我来说不太清楚。

另外:如何更改默认远程仓库而不进行本地分支追踪?

4个回答

19
如果您有多个远程存储库,并且没有指定任何远程存储库名称,则默认情况下将使用origin。如果没有名为 origin 的远程存储库,则会报错。
fatal: No remote repository specified.  Please, specify either a URL or a
remote name from which new revisions should be fetched.

另外:如何更改默认远程仓库而不使本地分支跟踪它?

您可以将该仓库重命名为“origin”以使其成为默认值。

注意:如果当前分支已经在不同的远程仓库上指定了上游,则此方法无效。从git help fetch

当未指定远程仓库时,默认使用origin远程仓库,除非为当前分支配置了上游分支。

在这种情况下,您可以通过编辑.git/config中配置的分支的remote字段来更改上游分支以使用origin


2
更改远程名称为origin没有其他替代方案吗? - Klas Mellbourn
7
让git默认将“origin”作为默认远程仓库有点不够灵活。我总是会将我的远程仓库重命名为更有意义的名称,比如“github”,“internal”等等。当然,如果“origin”远程仓库不存在,git会报错“fatal: No remote repository specified.” - Devy
1
@KlasMellbourn:你可以为跟踪分支设置远程仓库,使用不同于“origin”的远程仓库,然后当你检出其中一个分支并运行git fetch时,默认情况下将使用该远程仓库。 - ntc2
注意:在某些 Git 版本中,当唯一的远程库名称不是 origin 时,我曾经遇到过 git fetch 静默失败的情况。它没有任何致命错误或任何信息。它只是立即退出到提示符。一旦我将远程库重命名为 originfetch 命令就可以从远程库获取了。 - ADTC

4
在您的项目文件夹中,当您在第一步初始化git时,会创建.git文件夹。
查看此文件夹中名为config的文件,其中包含所有分支信息。默认情况下使用origin。
  [remote "origin"]
      fetch = +refs/heads/*:refs/remotes/origin/*
      url = git@github.com:project.git

因此,代码从此处列出的URL获取。


不需要这样做。您只需运行 git remote -v(查看所有)或 git remote get-url origin(检查默认值)。 - ADTC

2

它将获取源远程库。这是您执行 GIT clone 命令的第一个远程库。


3
也许您从未在仓库上执行过 git clone,而是事后添加了远程地址(称为“origin”或其他名称)。 - mwfearnley

0

以下是一些别名,可以用于编程:

branch-name = "symbolic-ref --short HEAD"  # https://dev59.com/Hm025IYBdhLWcg3wCxZN#19585361
branch-remote-fetch = !"branch=$(git branch-name \"$1\") && git config branch.\"$branch\".remote || echo origin #"
branch-remote-push  = !"branch=$(git branch-name \"$1\") && git config branch.\"$branch\".pushRemote || git config remote.pushDefault || git branch-remote-fetch #"
branch-url-fetch = !"remote=$(git branch-remote-fetch \"$1\") && git remote get-url        \"$remote\" #"  # cognizant of insteadOf
branch-url-push  = !"remote=$(git branch-remote-push  \"$1\") && git remote get-url --push \"$remote\" #"  # cognizant of pushInsteadOf

如果你想找到另一个分支的远程控制,那么请用以下内容替换上方的branch-name,允许传递单个参数:
branch-current = "symbolic-ref --short HEAD"  # https://dev59.com/Hm025IYBdhLWcg3wCxZN#19585361
branch-names = !"[ -z \"$1\" ] && git branch-current 2>/dev/null || git branch --format='%(refname:short)' --contains \"${1:-HEAD}\" #"  # https://dev59.com/Hm025IYBdhLWcg3wCxZN#19585361
branch-name = !"br=$(git branch-names \"$1\") && case \"$br\" in *$'\\n'*) printf \"Multiple branches:\\n%s\" \"$br\">&2; exit 1;; esac; echo \"$br\" #"

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