情景重现
你:面试官您好,我是xxx,毕业于xxx学校,工作xxx年,精通各种git命令。
面试官:您好您好,我问个常见的问题考察一下您的技术水平哈。请问,git pull和git fetch有什么区别,二者都在什么情况下使用?
你:emmmm...母鸡喔
面试官(微笑):回家等消息吧,有结果通知你~
二者区分
git fetch
首先我们来看一下git fetch的定义:
git fetch only downloads latest changes into the local repository.
It downloads fresh changes that other developers have pushed to
the remote repository since the late fetch and allows you to review
and merge manually at a later time using git merge.
Because it doesn't change your working directory or the staging area,
it is entirely safe, and you can run it as often as you want.
我们提取几个关键信息:
-
git fetch提取远端的最新改变到本地
-
git fetch不强行改变本地状态和预存区
-
可使用git merge手动合并
-
git fetch很安全
git pull
我们再看一下git pull的定义:
git pull downloads latest changes into the local repository
and it also automatically merges change in your working directory.
It doesn't give you a chance to review the changes before merging,
and as a consequence, 'merge conflicts' can and do occur. One important thing
to keep in mind is that it will merge only into the current working branch.
Other branches will stay unaffected.
我们再提取几个关键信息:
-
git pull直接将改动同步到本地工作区
-
git pull没机会做merge操作
-
git pull可能出现merge冲突
-
最好在同分支之间使用git pull,否则会出错误
总之:git pull = git fetch + git merge
二者在git中的位置
git fetch使用
- 获取远端分支的最新内容到FETCH_HEAD,并查看。
git fetch origin master
git log -p FETCH_HEAD
- 如果可以合并,就合并内容到本地
git merge
这里解释一下这个FETCH_HEAD, 它是一个版本链接,记录在本地一个文件中(.git/FETCH_HEAD),指向当前分支最新版本。
git pull使用
git pull的使用相当于上面两步的和,
git fetch origin master
git merge FETCH_HEAD
总结
此题不难,但答不上来的侮辱性极强。
本题主要考察的是git的基础知识,多看一些博客或者文章就可以搞定。
鸣谢
About me: 资深大猪蹄子