本地仓库推送到远程仓库:fatal: refusing to merge unrelated histories

最近,在操作git的时候,遇到各种问题,下面总结一下。

最开始,我不是先把远程仓库拉取到本地 ,而是直接在本地先创建一个仓库,再git remote add添加远程仓库。

当然,gitee官方还是有操作指南(在创建仓库后会显示)

首先,mkdir创建目录,在目录中添加内容,然后初始化为一个仓库,最后添加、提交到本地仓库。

添加远程仓库(注意:此时不会检查远程仓库是否存在,push的时候,如果不存在,会报错)

git remote add origin git@gitee.com:UncleYong/jmeter_dubbo_demo.git

注意:如果未配置ssh方式通信,就需要使用https地址:https://gitee.com/UncleYong/jmeter_dubbo_demo.git,否则push的时候会报错【详见:https://www.cnblogs.com/UncleYong/p/10676922.html

按照官方教程,执行git push -u origin master

报错:Updates were rejected because the remote contains work that you do not have locally

上图提示,向远程库推送的时候,要先进行pull,让本地新建的库和远程库进行同步

git pull,给出了两个操作方式

git pull 远程分支名 本地分支名

git pull origin master,报错fatal: refusing to merge unrelated histories

执行git branch --set-upstream-to=origin/master master,依然报错

或者不执行上面pull,直接git push -u origin master,报错:Updates were rejected because the tip of your current branch is behind its remote counterpart

 

网上有些说:先fetch,然后再merge,最后上传push,还是报错

错误提示:fatal: refusing to merge unrelated histories

其实这个问题是因为两个根本不相干的git库,一个是本地库,一个是远端库, 然后本地要去推送到远端, 远端觉得这个本地库跟自己不相干, 所以告知无法合并。解决方法:

第一种方法: 先从远端库拉下来,把本地要加入的代码放到刚刚从远端库下载到本地的库中,然后提交上去,因为这样的话,你基于的库就是远端的库,这是一次update操作

第二种方法:使用这个强制合并的方法

  git pull origin master --allow-unrelated-histories,后面加上--allow-unrelated-histories,把两个不相干的分支进行强行合并,后面再push就可以了

  git push origin master:init,origin是别名(git remote add origin git@gitee.com:UncleYong/test.git),master是本地的分支名字,init是远端要推送的分支名字,本地必须要先add、commit完了,才能推上去

  参考:http://stackoverflow.com/questions/37937984/git-refusing-to-merge-unrelated-histories

       https://dannyhz.iteye.com/blog/2412222

第三种方法:强制push,这样会使远程修改丢失,尤其是多人协作开发的时候,所以慎用。

  git push -u origin master -f

下面选择第二种方法

当前远程分支就下面一个文件

本地两个文件,一个同名的文件

执行git pull origin master --allow-unrelated-histories

这里不移除,也不移动,就改个名

git pull origin master --allow-unrelated-histories

按i,输入内容,esc,:wq退出

因为上面是改名,所以需要添加到本地仓库

最后,git push -u origin master

远程可以看到推送的内容

 至此,问题解决,所以,最好还是按照第一种方法操作,第二种方法如果同名的比较多,存在合并的问题,第三种会把远程的全部覆盖掉,不推荐。

原文地址:https://www.cnblogs.com/uncleyong/p/10654244.html