今天想把在公司写的一些代码上传的github上,将本地仓库和远程仓库关联起来,执行: 【git push -u origin main 】 把本地main branch的代码推送到远程的main branch时,报错:
! [rejected] main -> main (fetch first)
error: failed to push some refs to 'github.com:hijack-621/tpr-website.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.
查资料发现是因为我们在本地新建库后,与远程仓库的内容不一致导致的(远程仓库有一些内容本地没有)。
而且去查看远程分支:
Administrator@MS-TQHELRTLDMXE MINGW64 /d/phpstudy/WWW (develop) $ git branch -a * develop main
//只看到本地的分支!!!
使用命令:git remote update origin --prune --prune 去更新远程分支
再次查看所有分支:
Administrator@MS-TQHELRTLDMXE MINGW64 /d/phpstudy/WWW (main) $ git branch -a develop * main remotes/origin/develop remotes/origin/main
但是执行 【git push -u origin main 】 仍旧报错
! [rejected] main -> main (non-fast-forward) error: failed to push some refs to 'github.com:hijack-621/tpr-website.git' hint: Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g. hint: 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details.
意思大致是:你现在的分支被隐藏了...
不明白为什么会被隐藏【是不是我开了两个git bash 窗口, 用的同一个sshkey去操作的原因】,难怪 使用 -a 参数查看所有分支时,看不到远程分支呢。。。= 》》 解决方案:
使用 --force 参数,强制去提交【完成命令 git push -u --force origin main 】【推送本地git中的文件到远程的 main分支中】。【这里是 使用 gir push --help 】帮助命令时,在git 官方提供的 git-push manual page 页面中找到的方案! 下面是官方的解释!
--force Usually, the command refuses to update a remote ref that is not an ancestor of the local ref used to overwrite it. Also,
when --force-with-lease option is used, the command refuses to update a remote ref whose current value does not match what is expected. This flag disables these checks, and can cause the remote repository to lose commits; use it with care. Note that --force applies to all the refs that are pushed,
hence using it with push.default set to matching or with multiple push destinations configured with remote.*.push may overwrite refs other than the current branch (including local refs that are strictly behind their remote counterpart).
To force a push to only one branch, use a + in front of the refspec to push (e.g git push origin +master to force a push to the master branch).
See the <refspec>... section above for details.