有问题请指出
文章目录
2020/3/26 版本一
背景
本地仓库中有部分文件是以前上传到过远程仓库(github)的。现在又新建了在本地仓库新建了一个项目,想再合并提交到主干上。
按照以下命令:
//在当前目录新建一个Git代码库
$ git init
//添加当前目录的所有文件到暂存区
$ git add .
//提交暂存区到仓库区
$ git commit -m"提交信息"
//与远程仓库关联
$ git remote add origin [url]
//获取远程库与本地同步合并
$ git pull --rebase origin master
//把本地库的内容推送到远程
$ git push -u origin master
原因:git库中已经有部分代码了,不允许把代码上传远程库然后进行覆盖。需要更新再上传。
总结:如果pull不成功,是push不了的。
下图是pull失败截图
init一般也只要一次就够了,也不需要再次关联远程库了。
正确格式
//把远程仓库和本地同步,消除差异
git pull origin master --allow-unrelated-histories
$ git add .
$ git commit -m"提交信息"
$ git push
2020/4/7 版本二
1.fetch first
! [rejected] master -> master (fetch first)
error: failed to push some refs to ‘https://github.com/two-fire/Algorithm.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.
原因
创建repo时,选择了README初始化库,向Git repo add,commit一个README。但是local repo并不知道这个txt。所以当push时,导致Git认为你push时是想合并这两个库,它希望你能自己解决这件事。
解决
在$ git push origin master
前加一句$ git pull origin master
避免出现
1.创建新的库时,不要选择用README初始化,
这样push时就不会报错。
2.创建新的repo时,选择用README初始化,然后用$ git clone [URL]
在本地创建一个repo。之后和正常步骤一样,add、commit、push即可。
2.non-fast-forward
! [rejected] master -> master ( non-fast-forward)
error: failed to push some refs to ‘https://github.com/two-fire/Algorithm.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 push origin master
改成$ git push origin master --force
2020/4/11 版本三
fetch first
! [rejected] master -> master (fetch first)
error: failed to push some refs to ‘https://github.com/two-fire/Algorithm.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.
本地库和远程库文件删除的关系:
- 当我在本地库“实验一”中删除一个已经上传到github上的文件“login.txt”,然后在"实验一"中新建一个文件“1.txt”,之后再用add、commit、push origin master上传,成功。而且github上的“login.txt”依旧存在。
- 当我在github远程库上删除一个文件“.ignore.txt”,然后在"实验一"中新建一个文件“2.txt”,之后再用add、commit、push origin master上传,失败。报错如上。
如果我用2020/4/7 版本二
中的解决方法,加用pull origin master ,然后再push origin master,1.txt可以被成功上传,但是github里面“.ignore.txt”也会被删除。 - 如果我在github上直接编辑1.txt,然后将"实验一"中新建一个文件“3.txt”上传,也会报错。
这时候将本地库中的1.txt删除。git pull origin master
,本地库中的1.txt会再次出现变成github上修改过的内容(被merge了),但是之后再删除1.txt,git pull origin master
不会产生影响。
总之,git pull 非常危险,它其实包括了git fetch
和git merge
,会将远程库的更新合并到本地库。