解决 git push 无法push

怎么推不过去……

偶尔在这个时候推送指令的时候会出现错误信息:

1
2
3
4
5
6
7
8
9
10
$ git push

To https://github.com/eddiekao/dummy-git.git
! [rejected] master -> master (fetch first)
error: failed to push some refs to 'https://github.com/eddiekao/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 不让你推上。

怎么造成的?

通常情况会发生在多人一起的时候,想像一次这样的开发场景:

  1. Sherly 跟 Eddie 两个人在差不多的时间都从 Git Server 上拉了一份资料下来准备进行开发。
  2. 雪莉手脚比较快,先完成了,于是先把做好的成果推给了自己。
  3. 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/eddiekao/dummy-git

37aaef6..bab4d89 master -> origin/master

First, rewinding head to replay your work on top of it…

Applying: update index

这里加了 –rebase 参数是「内容抓下来之后请使用 Rebase 方式合并」表示,你想用一般的合并方式当然不会出现问题。

第二招:无视规则,总之就是听我的!**(误)**

凡事总有先来后到,在上面的例子中,谢利先推提出的内容,后推的人应该是拉下来更新的,食物照规定是推不上的。不过这也是有例外的,只要加上了 –force 主题词 -f ,它会强迫硬推上来,把雪莉先的内容盖掉:

$git push -f[origin master]

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/eddiekao/dummy-git.git

+ 6bf3967…c4ea775 master -> master (forced update)