同步远程分支时遇到的问题

bug详情

E:\program\git\14790897.github.io>git push origin main
To https://github.com/14790897/14790897.github.io
 ! [rejected]        main -> main (fetch first)
error: failed to push some refs to 'https://github.com/14790897/14790897.github.io'
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.

解决方法

这不是一个 bug,这是因为你的本地分支(main)落后于远程分支(origin/main)。Git 不允许直接将本地分支推送到远程分支,除非你的本地分支已经包含了远程分支的所有提交。这是为了避免在团队中多人协作时,覆盖其他人的工作。

在这种情况下,你需要先将远程分支的更改合并到本地分支,然后再将本地分支推送到远程分支。你可以按照下面的步骤操作:

  1. 使用 git fetch origin 命令,从远程仓库获取最新的提交,但不合并。

    git fetch origin
    
  2. 使用 git merge origin/main 命令,将获取到的远程分支(origin/main)合并到本地分支(main)。

    git merge origin/main
    

    如果合并过程中出现冲突,需要手动解决冲突并提交。

  3. 解决冲突并完成合并后,使用 git push origin main 命令将本地分支推送到远程分支。

    git push origin main
    

或者你也可以直接使用 git pull 命令,这个命令会执行 git fetchgit merge 两个步骤。

git pull origin main

然后解决冲突(如果有的话),完成合并后,再将本地分支推送到远程分支。