git fetch 的簡單用法:更新遠程代碼到本地倉庫

方式一
1. 查看遠程倉庫

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

從上面的結果可以看出,遠程倉庫有兩個,一個是eoecn,一個是origin
2 ,從遠程獲取最新版本到本地

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

$ git fetch origin master 這句的意思是:從遠程的origin倉庫的master分支下載代碼到本地的origin master
3. 比較本地的倉庫和遠程參考的區別

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

因爲我的本地倉庫和遠程倉庫代碼相同所以沒有其他任何信息
4. 把遠程下載下來的代碼合併到本地倉庫,遠程的和本地的合併

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

我的本地參考代碼和遠程代碼相同,所以是Already up-to-date

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

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

git fetch origin master:temp 這句命令的意思是:從遠程的origin倉庫的master分支下載到本地並新建一個分支temp

  1. 比較本地的倉庫和遠程參考的區別
1
2
$ git diff temp
su@SUCHANGLI /e/eoe_client/android-app (master)

命令的意思是:比較master分支和temp分支的不同
由於我的沒有區別就沒有顯示其他信息
4. 合併temp分支到master分支

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

由於沒有區別,所以顯示Already up-to-date.
合併的時候可能會出現衝突,有時間了再把如何處理衝突寫一篇博客補充上。
5.如果不想要temp分支了,可以刪除此分支

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

如果該分支沒有合併到主分支會報錯,可以用以下命令強制刪除git branch -D <分支名>

總結:方式二更好理解,更安全,對於pull也可以更新代碼到本地,相當於fetch+merge,多人寫作的話不夠安全。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章