偶尔在执行Push指令的时候会出现这个错误消息:
$ git push
To https://github.com/xxx/dummy-git.git
! [rejected] master -> master (fetch first)
error: failed to push some refs to 'https://github.com/xxx/dummy-git.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 push -u origin master)
这段消息的意思是在线版本的内容比你电脑里这份还要新,所以Git不让你推上去。
怎么造成的?
通常这个状况会发生在多人一起开发的时候,想像一下这个情境:
- Sherly跟Eddie两个人在差不多的时间都从Git Server上拉了一个资料下来准备进行开发。
- Sherly手脚比较快,先完成了,于是先把做好的成果推一份上去。
- Eddie不久后也完成了,但当他要推上去的时候发现推不上去了…
怎么解决?
解决方法算是有两招
第一招:先拉再推
因为你电脑里的内容是比较旧的,所以你应该先拉一份线上版本的回来更新,然后再推一次:
$ git pull --rebase
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 1), reused 3 (delta 1), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/xxx/dummy-git
37aaef6..bab4d89 master -> origin/master
First, rewinding head to replay your work on top of it...
Applying: update index
或
$ git pull origin master
$ git push -u origin master
这里加了--rebase参数是表示“内容抓下来之后请使用Rebase方式合并”,当然你想用一般的合并方式也没问题。合并如果没发生冲突,接下来应该就可以顺利往上推了。
第二招:无视规则,总之就是听我的(误)
凡事总有先来后到,在上面的示例中,Sherly先推上去的内容,后推的人就是应该拉一个下来更新,不然照规定是推不上去的。不过这规则也是有例外,只要加上了--force或是-f参数,它就会强迫硬推上去,把Sherly之前的内容盖掉:
$ git push -f
Counting objects: 19, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (17/17), done.
Writing objects: 100% (19/19), 2.16 KiB | 738.00 KiB/s, done.
Total 19 (delta 6), reused 0 (delta 0)
remote: Resolving deltas: 100% (6/6), done.
To https://github.com/xxx/dummy-git.git
+ 6bf3967...c4ea775 master -> master (forced update)
或
$ git push -u origin master -f
虽然关于这样的事情,但接下来你就要去面对Sherly,跟她解释为什么你把她的进度盖掉了。更多关于Force Push的说明,可参考「【状况题】听说git push- f这个指令很可怕,什么情况可以用它呢? 」章节介绍。
第三招: 若不想merge远程和本地修改,可以先创建新的分支:
$ git branch [name]
然后push
$ git push -u origin [name]