­

git fetch和git pull對比

情景重現

你:面試官您好,我是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.

我們提取幾個關鍵資訊:

  1. git fetch提取遠端的最新改變到本地

  2. git fetch不強行改變本地狀態和預存區

  3. 可使用git merge手動合併

  4. 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.

我們再提取幾個關鍵資訊:

  1. git pull直接將改動同步到本地工作區

  2. git pull沒機會做merge操作

  3. git pull可能出現merge衝突

  4. 最好在同分支之間使用git pull,否則會出錯誤

總之:git pull = git fetch + git merge

 

二者在git中的位置

image
 

git fetch使用

  1. 獲取遠端分支的最新內容到FETCH_HEAD,並查看。
git fetch origin master
git log -p FETCH_HEAD
  1. 如果可以合併,就合併內容到本地
git merge

這裡解釋一下這個FETCH_HEAD, 它是一個版本鏈接,記錄在本地一個文件中(.git/FETCH_HEAD),指向當前分支最新版本。

 

git pull使用

git pull的使用相當於上面兩步的和,

git fetch origin master
git merge FETCH_HEAD

 

總結

此題不難,但答不上來的侮辱性極強。

本題主要考察的是git的基礎知識,多看一些部落格或者文章就可以搞定。

 

鳴謝

git fetch vs git pull

git官網

git fetch & pull詳解

Tags: