当使用GitHub进行代码push是,出现了下面的错误,该如何是好?
错误描述:
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:Willido/First.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again. See the
'Note about fast-forwards' section of 'git push --help' for details.
出错原因:
git仓库中已经有一部分代码,导致远程仓库中代码版本与本地仓库中的不一致,所以它不允许你直接把你的代码覆盖上去。
解决办法:
1)强推
强行上传,即利用强覆盖方式使用本地的内容去替代git仓库中的内容,命令如下:
$ git push -f
2)先下载再上传
a.先将git仓库中的内容fetch即下载到你本地中,然后再merge,命令如下:
$ git fetch
$ git merge
也可以直接pull,命令如下:
$ git pull
但此时将又会出现另外的问题,错误信息如下:
You asked me to pull without telling me which branch you
want to merge with, and 'branch.master.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.
If you often merge with the same branch, you may want to
use something like the following in your configuration file:
[branch "master"]
remote = <nickname>
merge = <remote-ref>
[remote "<nickname>"]
url = <url>
fetch = <refspec>
See git-config(1) for details.
上面出现的 [branch "master"]是需要明确如下的内容(位于.git/config中)
[branch "master"]
remote = origin
merge = refs/heads/master
这是要告诉git两件事:
1.当你处于master branch, 默认的remote就是origin。
2.当你在master branch上使用git pull时,在没有指定remote和branch时,那么git就会采用默认的remote(即origin)来merge在master branch上所有的变更。
可以手工编辑config文件,也可以在终端上进行命令行编辑,所需命令行如下:
$ git config branch.master.remote origin
$ git config branch.master.merge refs
/heads/master
b.然后再重新pull一下,命令行如下:
$ git pull
c.最后再进行push,命令行如下:
$ git push