常用命令
git diff
先将当前git恢复到clean状态:
➜ mygit git:(master) ✗ git checkout helloworld.txt
➜ mygit git:(master) git status
On branch master
nothing to commit, working directory clean
执行2次修改操作后,git区域内容变为:
执行git diff helloworld.txt
:
diff --git a/helloworld.txt b/helloworld.txt
index 65d1b62..aadbd9b 100644
--- a/helloworld.txt
+++ b/helloworld.txt
@@ -1,2 +1,3 @@
Hello git !
beijing
+China
git diff对比的是工作目录和暂存区,65d1b62是该文件在暂存区的哈希值,aadbd9b是该文件在工作目录的哈希值,100644指对象的模式,100644表示普通对象。
执行git diff --cached helloworld.txt
:
diff --git a/helloworld.txt b/helloworld.txt
index 2effaac..65d1b62 100644
--- a/helloworld.txt
+++ b/helloworld.txt
@@ -1 +1,2 @@
Hello git !
+beijing
git diff –cached对比的是git仓库和暂存区,2effaac是该文件在仓库的哈希值,即最后一次commit的id。
执行git diff HEAD helloworld.txt
:
diff --git a/helloworld.txt b/helloworld.txt
index 2effaac..aadbd9b 100644
--- a/helloworld.txt
+++ b/helloworld.txt
@@ -1 +1,3 @@
Hello git !
+beijing
+China
git diff HEAD对比的是git仓库和工作目录。
git checkout
执行git status命令:
➜ mygit git:(master) ✗ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: helloworld.txt
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: helloworld.txt
执行checkout后:
➜ mygit git:(master) ✗ git checkout helloworld.txt
➜ mygit git:(master) ✗ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: helloworld.txt
现在只显示说暂存区有changes待提交,那工作目录的变动上哪儿了呢?我执行➜ mygit git:(master) ✗ git diff helloworld.txt
没有任何输出,说明工作目录和暂存区已经同步了,为了打消我的疑虑,我现在看看helloworld.txt内容到底变成了什么样子:
➜ mygit git:(master) ✗ cat helloworld.txt
Hello git !
beijing
的确,工作目录中的China
消失了,跟暂存区内容一样了,我再看看仓库有没有变化:
➜ mygit git:(master) ✗ git diff --cached helloworld.txt
diff --git a/helloworld.txt b/helloworld.txt
index 2effaac..65d1b62 100644
--- a/helloworld.txt
+++ b/helloworld.txt
@@ -1 +1,2 @@
Hello git !
+beijing
可以看到,暂存区比仓库多了beijing
,那么说明仓库没变动,还是原来的Hello git !
执行完checkout之后,工作目录的changes提示信息消失了,当前状态只显示暂存区有待commit的changes。说明git checkout操作是从暂存区到工作目录,用最后一次add操作覆盖工作目录,与git仓库无关。
git reset
目前,git区域的内容如下所示:
执行git reset命令:
➜ mygit git:(master) ✗ git reset helloworld.txt
Unstaged changes after reset:
M helloworld.txt
提示信息说,已经将helloworld.txt的变化unstage了,意味着暂存区的变化消除了,那暂存区变成什么样子了呢?
➜ mygit git:(master) ✗ git diff helloworld.txt
diff --git a/helloworld.txt b/helloworld.txt
index 2effaac..65d1b62 100644
--- a/helloworld.txt
+++ b/helloworld.txt
@@ -1 +1,2 @@
Hello git !
+beijing
工作目录比暂存区多了beijing
,那是不是意味着暂存区现在跟仓库一样,都是Hello git !
呢?确认一下:
➜ mygit git:(master) ✗ git diff --cached helloworld.txt
什么都没输出,果然,暂存区跟仓库同步了。因此,git reset操作是从git repository到staging area,与工作目录无关。使用HEAD指针指向的分支的commit来覆盖暂存区。
当然我们这种说法是不严谨的,git reset命令常用的有2个选项,–mixed,–hard,前者是默认情况,我们上面演示的就是–mixed,它只用仓库来覆盖暂存区。而–hard的威力更强劲,执行git reset –hard命令会用HEAD覆盖暂存区和工作目录。