git fetch
使用git的同学肯定用过git fetch这个命令,没用过也至少听过或者看过的吧?关于这个命令还是有必要讨论一下的。下面就用实例讨论下git fetch repo和git fetch repo branch-name的区别。
1.我们新建一个目录,然后初始化一下git仓库,做一次简单的提交(commit):
mkdir sample-git
cd sample-git/
git init
touch .gitignore
git add .
git commit -am "init"
2.添加一个远程仓库(repo):
git remote add repo git@github.com:zhuqingcode/sample-git.git
3.查看一下repo的情况:
linux-geek:/home/tmp/sample-git # git remote show repo
Enter passphrase for key '/root/.ssh/id_rsa':
* remote repo
Fetch URL: git@github.com:zhuqingcode/sample-git.git
Push URL: git@github.com:zhuqingcode/sample-git.git
HEAD branch (remote HEAD is ambiguous, may be one of the following):
b0
b1
Remote branches:
b0 new (next fetch will store in remotes/repo)
b1 new (next fetch will store in remotes/repo)
到这里我们大致了解了repo是有两个分支构成的,即b0 b1。
4.我们单独git fetch一个分支看看:
linux-geek:/home/tmp/sample-git # git fetch repo b0
Enter passphrase for key '/root/.ssh/id_rsa':
remote: Counting objects: 24, done.
remote: Compressing objects: 100% (8/8), done.
remote: Total 24 (delta 0), reused 22 (delta 0)
Unpacking objects: 100% (24/24), done.
From github.com:zhuqingcode/sample-git
* branch b0 -> FETCH_HEAD
它不会在本地创建一个远程repo/b0的副本,而是直接更新到FETCH_HEAD上了,用FETCH_HEAD直接指向了远程repo/b0最近一次commit。我们来git show看一下
linux-geek:/home/tmp/sample-git # git show FETCH_HEAD
commit 8d0235fd5a1d990354341a693066dc3a17884349
Author: zhuqing <zhuqinggooogle@gmail.com>
Date: Mon Aug 12 16:01:53 2013 +0800
add 5
diff --git a/README.md b/README.md
index 94ebaf9..8a1218a 100644
--- a/README.md
+++ b/README.md
@@ -2,3 +2,4 @@
2
3
4
+5
lines 1-15/15 (END)
我们也能看到其修改了哪些东西,我们甚至也能直接合并FETCH_HEAD到本地分支master上来:
linux-geek:/home/tmp/sample-git # git merge FETCH_HEAD
Merge made by recursive.
README.md | 5 +++++
1 files changed, 5 insertions(+), 0 deletions(-)
create mode 100644 README.md
5.相反,如果我们直接git fetch远程仓库来看看:
linux-geek:/home/tmp/sample-git # git fetch repo
Enter passphrase for key '/root/.ssh/id_rsa':
From github.com:zhuqingcode/sample-git
* [new branch] b0 -> repo/b0
* [new branch] b1 -> repo/b1
看到区别了吗?它会在本地本地创建一个远程repo/b0和repo/b1的副本,我们来git show看一下:
linux-geek:/home/tmp/sample-git # git show repo/b0
commit 8d0235fd5a1d990354341a693066dc3a17884349
Author: zhuqing <zhuqinggooogle@gmail.com>
Date: Mon Aug 12 16:01:53 2013 +0800
add 5
diff --git a/README.md b/README.md
index 94ebaf9..8a1218a 100644
--- a/README.md
+++ b/README.md
@@ -2,3 +2,4 @@
2
3
4
+5
你会发现代码的变化是一样的,没有任何区别。同样也可以合并到本地上的分支上来!