首页 > 解决方案 > Github 错误“更新被拒绝,因为您当前分支的尖端落后”

问题描述

我试图在 github 中启动一个新项目这些是导致此错误的步骤:

在github新建一个仓库,复制链接https://github.com/username/repository.git

>cd to project folder

>git init

>git remote add origin https://github.com/username/repository.git

>git add -A

>git status

>git commit -m "adding files"

>git push origin master

错误:

 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/username/repository.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

我试图做一个>git pull,但我得到一个不同的错误

There is no tracking information for the current branch.
Please specify which branch you want to merge with.

接下来我尝试了上面的建议

>git pull origin master
From https://github.com/username/repository.git
 * branch            master     -> FETCH_HEAD
fatal: refusing to merge unrelated histories

我在网上找到了一个解决方案,这是一个修复,但它并没有告诉我我在 git 命令序列中做错了什么

>git pull origin master --allow-unrelated-histories

标签: gitgithubrepository

解决方案


混帐初始化

那是你做错了。你应该已经从 github 克隆了 repo。


详细说明。你在 github 上新建了一个仓库

在github新建一个仓库,复制链接https://github.com/username/repository.git

把这想象成 SSH 进入 github.com 并做git init. 这会初始化,即在 master 上为空白 repo 创建第一个提交。

然后。在本地,您也这样做了git init

这使用 master 上的提交初始化了一个新的本地 repo。

在这个阶段,您有 2 个不同的 repo(一个本地 / 一个远程),尽管 blob 的哈希值相同(假设两个 repo 都是空的),但树结构和 refs 可能不同。这意味着初始提交哈希是不同的。这是我对您收到错误的原因的猜测:

hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref.

这也是为什么 pull 不会做任何事情的原因。拉取只是一个提取/合并操作的组合。

但是,如果您考虑您的情况,即使您在添加文件并在本地提交之前拉取,它仍然是 2 个 repo(本地/远程),在初始提交时可能具有不同的提交哈希......您在机器上本地初始化的那个认为它是提交哈希是正确的。您在 github 上初始化的那个认为它的提交是正确的。


推荐阅读