git fetch 的简单用法:更新远程代码到本地仓库及冲突处理

Git中从远程的分支获取最新的版本到本地方式如下,
如何更新下载到代码到本地,请参阅ice的博客基于Github参与eoe的开源项目指南
方式一
1. 查看远程仓库

 
     
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
 
     
  1. $ git remote -v
  2. eoecn https://github.com/eoecn/android-app.git (fetch)
  3. eoecn https://github.com/eoecn/android-app.git (push)
  4. origin https://github.com/com360/android-app.git (fetch)
  5. origin https://github.com/com360/android-app.git (push)
  6. su@SUCHANGLI /e/eoe_client/android-app (master)

从上面的结果可以看出,远程仓库有两个,一个是eoecn,一个是origin
2 ,从远程获取最新版本到本地

 
     
  1. 1
  2. 2
  3. 3
  4. 4
 
     
  1. $ git fetch origin master
  2. From https://github.com/com360/android-app
  3. * branch master -> FETCH_HEAD
  4. su@SUCHANGLI /e/eoe_client/android-app (master)

$ git fetch origin master 这句的意思是:从远程的origin仓库的master分支下载代码到本地的origin master
3. 比较本地的仓库和远程参考的区别

 
     
  1. 1
  2. 2
 
     
  1. $ git log -p master.. origin/master
  2. su@SUCHANGLI /e/eoe_client/android-app (master)

因为我的本地仓库和远程仓库代码相同所以没有其他任何信息
4. 把远程下载下来的代码合并到本地仓库,远程的和本地的合并

 
     
  1. 1
  2. 2
  3. 3
 
     
  1. $ git merge origin/master
  2. Already up-to-date.
  3. su@SUCHANGLI /e/eoe_client/android-app (master)

我的本地参考代码和远程代码相同,所以是Already up-to-date

以上的方式有点不好理解,大家可以使用下面的方式,并且很安全
方式二
1.查看远程分支,和上面的第一步相同
2. 从远程获取最新版本到本地

 
     
  1. 1
  2. 2
  3. 3
  4. 4
 
     
  1. $ git fetch origin master:temp
  2. From https://github.com/com360/android-app
  3. * [new branch] master -> temp
  4. su@SUCHANGLI /e/eoe_client/android-app (master)

git fetch origin master:temp 这句命令的意思是:从远程的origin仓库的master分支下载到本地并新建一个分支temp

  1. 比较本地的仓库和远程参考的区别
 
     
  1. 1
  2. 2
 
     
  1. $ git diff temp
  2. su@SUCHANGLI /e/eoe_client/android-app (master)

命令的意思是:比较master分支和temp分支的不同
由于我的没有区别就没有显示其他信息
4. 合并temp分支到master分支

 
     
  1. 1
  2. 2
  3. 3
 
     
  1. $ git merge temp
  2. Already up-to-date.
  3. su@SUCHANGLI /e/eoe_client/android-app (master)

由于没有区别,所以显示Already up-to-date.
如果系统中有一些配置文件在服务器上做了配置修改,然后后续开发又新添加一些配置项的时候,

在发布这个配置文件的时候,会发生代码冲突:

error: Your local changes to the following files would be overwritten by merge:

    protected/config/main.php

    Please, commit your changes or stash them before you can merge.

如果希望保留生产服务器上所做的改动,仅仅并入新配置项, 处理方法如下:

  git stash

  git pull

  git stash pop

  然后可以使用git diff -w +文件名 来确认代码自动合并的情况.

反过来,如果希望用代码库中的文件完全覆盖本地工作版本. 方法如下:

  git reset --hard

  git pull

  其中git reset是针对版本,

  如果想针对文件回退本地修改,使用

git checkout HEAD file/to/restore

5.如果不想要temp分支了,可以删除此分支

 
     
  1. 1
  2. 2
  3. 3
 
     
  1. $ git branch -d temp
  2. Deleted branch temp (was d6d48cc).
  3. su@SUCHANGLI /e/eoe_client/android-app (master)

如果该分支没有合并到主分支会报错,可以用以下命令强制删除git branch -D <分支名>

总结:方式二更好理解,更安全,对于pull也可以更新代码到本地,相当于fetch+merge,多人写作的话不够安全。
如有错误请指正

Supongo que te gusta

Origin blog.csdn.net/zyu67/article/details/120128943
Recomendado
Clasificación